だから私はメタクラスをとても楽しみにしていました。その後、メタクラスを追加する前に、まず言語でリフレクションと具体化が必要だと彼らは考えているため、 c++23には含まれないだろうと聞きました。
C++23のリフレクションを見ると、具体化機能があるようです。メタクラスが何をするかを解決するのに十分ですか。つまり、メタクラスは単なるシンタックス シュガーですか?
現在の提案を使用して、次のような型を書いている人を複製できますか:
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、どちらも私がメタクラスに興奮した種類の例です。
構文についてはあまり心配していません (ライブラリを記述して poly 値またはインターフェイスを作成できることは便利ですが、正確な構文はそうではありません)。