我能想到的使用其模板类型的静态方法的最简单示例是这个 create()
函数。
struct Foo {
template <typename T = Foo>
static T *create() {
return new T();
}
};
struct Bar : Foo {};
struct Baz : Foo {};
int main() {
Foo::create();
Bar::create<Bar>();
// Bar::create(); // Misleading, creates a Foo instead of Bar
return 0;
}
我的问题是:有什么我可以添加到 Foo::create()
静态方法中,自动检测它是从哪个类调用的,以避免重复指定类名,即Bar::create()
?我想在不向 Bar
和 Baz
或 Foo< 的任何其他后代添加
(因为可能有数千个)。create()
静态方法的情况下执行此操作
也许有一些神奇的关键字可以做到这一点?
template <typename T = this_type>
最佳答案
我能想到的最好的是CRTP:
template<class T>
struct Base {
static T *create() {
return new T();
}
};
struct Foo : public Base<Foo> {};
struct Bar : public Base<Bar> {};
struct Baz : public Base<Baz> {};
int main() {
Foo* foo = Foo::create();
Bar* bar = Bar::create();
return 0;
}
关于c++ - 在子类上调用模板化静态方法时获取类的类型名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50506725/