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.

Community
  • 1
  • 1
mclaassen
  • 5,018
  • 4
  • 30
  • 52
  • 2
    Are your overridden methods in the header file? Or the cpp file? IF they're in the cpp file, they need to be in the header file: http://stackoverflow.com/questions/1353973/c-template-linking-error – JaredC Jan 05 '13 at 03:39
  • 1
    I suspect you need to read this: http://www.parashift.com/c++-faq/separate-template-fn-defn-from-decl.html. – Oliver Charlesworth Jan 05 '13 at 03:41

1 Answers1

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

Community
  • 1
  • 1
JaredC
  • 5,150
  • 1
  • 20
  • 45
  • 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 05 '13 at 03:59
  • @jogojapan Oli's link above mentions that, but I pointed to the more general FAQ topic. Thanks for pointing this out. – JaredC Jan 05 '13 at 04:10