|
|
|
|
|
by chrisaycock
3155 days 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/p070... |
|