【问题标题】:Using Template Member data使用模板成员数据
【发布时间】:2015-04-14 12:52:13
【问题描述】:

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

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

Print 函数将根据 T 的类型进行打印,它是 int 还是 float。 此时我收到链接器错误。

错误 LNK2019:未解析的外部符号“公共:__thiscall 模板动态::模板动态(无效)“ (??0?$templateDynamic@H@@QAE@XZ) 在函数“public: __thiscall Holder::Holder(void)" (??0Holder@@QAE@XZ)

【问题讨论】:

标签: c++


【解决方案1】:

您还没有为templateDynamicHolder 定义构造函数

【讨论】:

  • 那不是原因。我有这个实现。刚刚在发布的示例中遗漏了。我的坏
  • @surega:你定义了Holder::Holder(int a),但你的班级有Holder::Holder()。您需要更改其中一个。
猜你喜欢
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多