【问题标题】:Static function in template class模板类中的静态函数
【发布时间】:2012-05-22 04:22:46
【问题描述】:

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

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

我已经知道了:

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()

【问题讨论】:

标签: c++ function templates static


【解决方案1】:

CreateBase 函数是在基类型中定义的,所以直接调用它:

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

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

【讨论】:

  • 问题不是我不能调用它,而是这段代码没有链接。
  • @Neil:在Create 中,您正在调用未定义的Type&lt;&gt;::CreateBase,因此链接器失败。建议的解决方案是调用Type&lt;&gt;::CreateBase(甚至不要声明它!)并直接调用Base::CreateBase,它在MyType中定义并且将适当地链接。
【解决方案2】:

找到了。

问题是我没有调用派生类的函数。

这里是修复:

static void Create()
{
    mBase = T::CreateBase();
}

【讨论】:

    猜你喜欢
    • 2012-03-09
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    相关资源
    最近更新 更多