c++ - 模板类中的静态函数

标签 c++ function templates static

我正在尝试在模板中创建一种工厂类。我想做一些类似于纯虚函数的事情,但它需要是静态的,因为我正在使用该函数来创建类型。

我想要发生的是当我声明一个类时,模板调用静态函数。静态函数实际上是在模板化类中声明的。

我已经做到了:

class Base
{

};

template<typename T>
class Type : public Base
{
public:
    static void Create()
    {
        mBase = CreateBase();
    }

private:
    static Base* CreateBase();

    static Base* mBase;
};

class MyType : public Type<MyType>
{
private:        
    static Base* CreateBase()
    {
        return new MyType;
    }
};

template<typename T>
Base* Type<T>::mBase = NULL;

void test()
{
    MyType::Create();
}

我收到链接时间错误:

undefined reference to `Type<MyType>::CreateBase()

最佳答案

CreateBase函数定义在基类型中,所以直接调用即可:

template<typename T>
class Type : public Base
{
public:
    static void Create()
    {
        mBase = Base::CreateBase();
    }
//...

无需在模板中声明另一个CreateBase

关于c++ - 模板类中的静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10587482/

相关文章:

c++ - 无法使用 cmake + vcpkg 在 VS Code 中包含 C++ 项目的库

javascript - 在 JavaScript 中,f 是什么意思?

c++ - Variadic 模板模拟 "runtime"扩展

visual-studio-2010 - Visual Studio如何生成类模板?

c++ - 使用自定义删除器为 unique_ptr 返回 nullptr 失败

c++ - 使用移动语义将基类实例插入子类实例

c++ - 使用GDB查找某个函数对应的内存地址/调试

c++:在外部声明和填充 map

Python 诅咒 : module function vs instance function

python - 无法更改Python中全局变量的值