【发布时间】:2021-08-04 18:58:31
【问题描述】:
所以我一直很期待metaclasses。然后我听说它不会出现在 c++23 中,因为他们认为我们首先需要在语言中进行反射和具体化,然后才能添加元类。
查看c++23 反射,似乎有具体化能力。它们是否足以解决元类的作用?即,元类只是语法糖吗?
使用current proposal,我们可以复制某人编写如下类型:
interface bob {
void eat_apple();
};
并生成如下类型:
struct bob {
virtual void eat_apple() = 0;
virtual ~bob() = default;
};
为了更进一步,采取类似于
vtable bob {
void eat_apple();
~bob();
};
poly_value bob_value:bob {};
并且能够生成
// This part is optional, but here we are adding
// a ADL helper outside the class.
template<class T>
void eat_apple(T* t) {
t->eat_apple();
}
struct bob_vtable {
// for each method in the prototype, make
// a function pointer that also takes a void ptr:
void(*method_eat_apple)(void*) = 0;
// no method_ to guarantee lack of name collision with
// a prototype method called destroy:
void(*destroy)(void*) = 0;
template<class T>
static constexpr bob_vtable create() {
return {
[](void* pbob) {
eat_apple( static_cast<T*>(pbob) );
},
[](void* pbob) {
delete static_cast<T*>(pbob);
}
};
}
template<class T>
static bob_vtable const* get() {
static constexpr auto vtable = create<T>();
return &vtable;
}
};
struct bob_value {
// these should probably be private
bob_vtable const* vtable = 0;
void* pvoid = 0;
// type erase create the object
template<class T> requires (!std::is_base_of_v< bob_value, std::decay_t<T> >)
bob_value( T&& t ):
vtable( bob_vtable::get<std::decay_t<T>>() ),
pvoid( static_cast<void*>(new std::decay_t<T>(std::forward<T>(t))) )
{}
~bob_value() {
if (vtable) vtable->destroy(pvoid);
}
// expose the prototype's signature, dispatch to manual vtable
// (do this for each method in the prototype)
void eat_apple() {
vtable->method_eat_apple(pvoid);
}
// the prototype doesn't have copy/move, so delete it
bob_value& operator=(bob_value const&)=delete;
bob_value(bob_value const&)=delete;
};
Live example,这两个都是我对元类感到兴奋的例子。
我不太担心语法(能够编写一个库并创建多值或接口只是有用,确切的语法不是),但我担心它能够做到这一点。
【问题讨论】:
-
我不确定我是否理解这个问题。元类只是反射的一个方面——它们是特定类型代码注入的语法糖。
-
@Barry 我在问反射提案现有的具体化功能是否强大到足以生成与元类相同的结果。是 just 语法糖吗?还是元类提案提供了更多的权力?我认为答案是“只是糖”,但我不确定,因此提出了这个问题。
-
来自P2237:“实现这项工作的实际机制是一个词法技巧;元类只是第 6 节和第 7 节中描述的特性之上的语法糖。”
-
@Barry 所以这看起来像是一个“我们不需要元类来做这个”的答案,甚至是一个显示它的引用。 :)
标签: c++23 c++23 c++ metaclass reification c++23 static-reflection