surega
surega

Reputation: 715

Using Template Member data

I was trying to use a template based class as a member of another class. This other class will decide based on its data member value what is the data type that the template based member should use. To this end I used bit of polymorphism to decide on run time the instantiation.

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 function will then print based on the type of T is it an int or float. I am getting a linker error at this point.

error LNK2019: unresolved external symbol "public: __thiscall templateDynamic::templateDynamic(void)" (??0?$templateDynamic@H@@QAE@XZ) referenced in function "public: __thiscall Holder::Holder(void)" (??0Holder@@QAE@XZ)

Upvotes: 0

Views: 53

Answers (1)

NathanOliver
NathanOliver

Reputation: 180805

You have not defined the constructor for templateDynamic and Holder

Upvotes: 2

Related Questions