2

Possible Duplicate:
C++ template, linking error
Undefined symbol on a template operator overloading function

So I have an abstract Button class:

class Button
{
public:
    int x, y, width, height;
    std::string label, text;
    bool checkForClick(int mouseX, int mouseY);
    virtual void click(int mouseX, int mouseY) =0;
    virtual void draw(); //has a default implementation which can be overridden
};

and a subclass which I want to be a template class:

template <typename T>
class IncrementButton : public Button
{
public:
    T& controlValue;
    T increment;
    T minVal, maxVal;

    IncrementButton(T& controlValue) : controlValue(controlValue) {}

    void click(int mouseX, int mouseY);
    void draw(); 
};

The overridden methods look like:

template <typename T>
void IncrementButton<T>::click(int mouseX, int mouseY)
{
    //do something with controlValue
}

template <typename T>
void IncrementButton<T>::draw()
{
    //use value of controlValue
}

but this won't compile. It gives me the error:

Error   1   error LNK2001: unresolved external symbol "public: virtual void __thiscall IncrementButton<float>::click(int,int)" (?click@?$IncrementButton@M@@UAEXHH@Z)

...and the same thing for draw()

Any ideas? I'm relatively new to C++ so I'm hoping maybe there's something silly I'm doing wrong.

2

1 Answer 1

0

You can fix your problem by moving your definitions into the header file. There are other solutions though too, but I'll let others explain them better-- see these links:

FAQ

Another Answer

2
  • The other solution, which is not actually explained by the answer linked here, is to use an explicit instantiation in the .cpp file where the template functions are defined. I think it's important to mention this, although putting all definitions into the header is typically the preferred solution.
    – jogojapan
    Jan 5, 2013 at 3:59
  • @jogojapan Oli's link above mentions that, but I pointed to the more general FAQ topic. Thanks for pointing this out.
    – JaredC
    Jan 5, 2013 at 4:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.