c++ - 在子类上调用模板化静态方法时获取类的类型名称

标签 c++

我能想到的使用其模板类型的静态方法的最简单示例是这个 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()?我想在不向 BarBazFoo< 的任何其他后代添加 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/

相关文章:

c++ - "Attempting to reference a deleted function"添加 QMutex 到类后

c++ - OpenCV Feature2D 类中 CV_WRAP 和 CV_OUT 的含义是什么

c++ - 查找小字符串在大字符串中的次数 (c++)

c++ - __time32_t 时间精度?

c++ - GCC 6.x 关于 lambda 可见性的警告

c++ - 在类的方法中初始化类的对象成员

c++ - 如何使用 winsock 1.1 版实现 icmp 数据包处理程序?

c++ - 使用 PortAudio 录制音频

c++ - 通过函数返回枚举

c++ - 如何创建指向无法修改指向地址的数组的指针?