0

I have a compiler error that exhibits itself when I use a template on a static class function.

Why does this happen and how can I fix it?

Error:

Error 1 error LNK2019: unresolved external symbol "public: static class CStatus const __cdecl CustomWindowComponent::setHWNDComponent(struct HWND__ *,class WindowComponent *)" (??$setHWNDComponent@VWindowComponent@@@CustomWindowComponent@@SA?BVCStatus@@PAUHWND__@@PAVWindowComponent@@@Z) referenced in function _wWinMain@16 D:\Demo_Project\main.obj Demo_Project

The following code causes the compiler error and the next sample does not:

// Causes error WHEN the function is used
class CustomWindowComponent : public Component
{
public:

    template <typename T>
    static void setHWNDComponent(HWND hwnd, T* cmp)
    {

    }
    ...

// No error
class CustomWindowComponent : public Component
{
public:

    static void setHWNDComponent(HWND hwnd, Component* cmp)
    {

    }
    ...

// in main compile error occurs here
CustomWindowComponent::setHWNDComponent<WindowComponent>(myHwnd, cmp.get());

*Note: In my project the static function is defined in the header file and implemented in its .cpp file. I've merged them for brevity in this post.

sazr
  • 24,984
  • 66
  • 194
  • 362
  • If it's going to be a template function you either need the implementation in the header or you need to explicitly instantiate it. – kfsone May 24 '16 at 23:43
  • @kfsone is that a rule that applies to all class template functions or just static class template functions? For class template functions, I pretty much always define in the header and implement in the cpp file. – sazr May 24 '16 at 23:45
  • @JakeM It applies to all templates. – user253751 May 24 '16 at 23:49
  • @immibis & kfsone thanks for the comments. Would you be able to provide an example of 'explicitly instantiating it' as kfsone said? – sazr May 24 '16 at 23:51

0 Answers0