使用模板成员数据

时间:2015-02-13 13:06:04

标签: c++

我试图将基于模板的类用作另一个类的成员。此其他类将根据其数据成员值决定基于模板的成员应使用的数据类型。为此,我使用了一些多态来决定实例化的运行时间。

class Base
{
public:
    virtual void print() = 0;
};

template <typename T>
class templateDynamic : public Base
{
public:
    templateDynamic();
    ~templateDynamic();
    void print();
};

    template <typename T>
templateDynamic<T>::templateDynamic()
{
}

template <typename T>
templateDynamic<T>::~templateDynamic()
{
}

template <typename T>
void templateDynamic<T>::print()
{

}

class Holder
{
private:
    Base * m_ABC;
public:
    Holder(int a);  
    void print();
};

void Holder::print()
{
    m_ABC->print();
}

Holder::Holder(int a)
{
    if(a == 1)
      m_ABC = new templateDynamic<int>();
    else
      m_ABC = new templateDynamic<float>();
}

int main()
{
    Holder aHolder(1);
    aHolder.print();
    Holder aHolder2(2);
    aHolder.print();
}

然后打印功能将根据T的类型进行打印是int还是float。 我此时收到链接器错误。

  

错误LNK2019:未解析的外部符号&#34; public:__ thishisall   templateDynamic :: templateDynamic(无效)&#34;   (?0?$ templateDynamic @ H @@ QAE @ XZ)在函数&#34; public中引用:   __thiscall Holder :: Holder(void)&#34; (?? 0Holder @@ @ QAE XZ)

1 个答案:

答案 0 :(得分:2)

您尚未定义templateDynamicHolder

的构造函数