4 ms·
The interview covers proposed metaprogramming features in upcoming versions of C++. In particular, it demonstrates metaclass as a way for users to define new ki
by chrisaycock 9y ago
The interview covers proposed metaprogramming features in upcoming versions of C++. In particular, it demonstrates metaclass as a way for users to define new kinds of types, instead of relying solely on class/struct/union/enum.
For example, Java has an interface, in which methods are declared but not defined. The proposal for metaclass gives a demonstration of what an interface in C++ could look like:
interface Shape {
int area() const;
void scale_by(double factor);
};
Instead of changing the compiler to allow for new interface keyword, we can create a metaclass:
// the dollar sign ($) prefix indicates reflection and metaprogramming
$class interface {
// the constexpr indicates compile-time execution
constexpr {
// raise an error if there are data members
compiler.require($interface.variables().empty(),
"interfaces may not contain data");
// loop over all functions
for (auto f : $interface.functions()) {
// raise an error if move/copy functions are present
compiler.require(!f.is_copy() && !f.is_move(),
"interfaces may not copy or move");
// function must be public
if (!f.has_access())
f.make_public();
compiler.require(f.is_public(),
"interface functions must be public");
// function must be virtual
f.make_pure_virtual();
}
}
// add a destructor
virtual ~interface() noexcept { }
};
Thus I can create a new kind of type directly in my code. This can be part of a library for downstream users without ever changing the compiler.
See the full proposal here:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0707r2.pdf http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p070...
- xamuel 9y agoThat is not a step toward simpler code. Under that proposal, people looking at your code will have to look up definitions of basic things that ought to be keywords---like "interface"---in order to reason about the code.
- jcelerier 9y ago> Under that proposal, people looking at your code will have to look up definitions of basic things that ought to be keywords---like "interface"---in order to reason about the code. That's a good thing: now you can refer to 20 lines of code instead of 15 pages of standardese to understand what happens.
- xamuel 9y agoI can learn the 15 pages of standardese and it'll apply uniformly to every program. The 20 lines will contain some subtle surprise at the worst possible time.
- jcelerier 9y ago> I can learn the 15 pages of standardese and it'll apply uniformly to every program. That's assuming the compilers implementors had the same interpretation than you. With code, there is much less room for interpretation.
- nikbackm 9y agoNot really a problem, if a "basic thing" is common enough you just put it into a library. Maybe even the C++ standard library. The "interface" definition should probably qualify for that.