这个问题与使用 std::variant 强制使用通用接口,无需继承 https://stackoverflow.com/questions/72434897/enforcing-a-common-interface-with-stdvariant-without-inheritance.
这个问题和这个问题之间的区别在于,我不介意继承,我只是在寻找以下结构/类......
struct Parent { virtual int get() = 0; };
struct A : public Parent { int get() { return 1; } };
struct B : public Parent { int get() { return 2; } };
struct C : public Parent { int get() { return 3; } };
...自动“组装”到模板中:
template<typename PARENT, typename... TYPES>
struct Multi
{
// magic happens here
}
// The type would accept assignment just like an std::variant would...
Multi<Parent, A, B, C> multiA = A();
Multi<Parent, A, B, C> multiB = B();
Multi<Parent, A, B, C> multiC = C();
// And it would also be able to handle virtual dispatch as if it were a Parent*
Multi<Parent, A, B, C> multiB = B();
multiB.get(); // returns 2
这可能吗?如果是这样,怎么办?我想避免使用处理指针,因为使用 std::variant/unions 的目的是使内存连续。