2017-07-01 103 views
-3

我正尝试创建一个通用按钮,并且希望能够传递一个函数以在单击它时调用它。传递函数指针时无法解析的外部符号

main.cpp中:

#include "Window.h" 

int testfunction() { 
    print("Test"); 
    return 1; 
} 

...other stuff... 

window->SetButtonFunction_NoArgs<int>(" *unrelated stuff* ", &testfunction); 

窗口是一个WindowMain类:

window.h中:

class WindowMain { 
    *Stuff* 
    template <class R1> void SetButtonFunction_NoArgs(string id, R1(*func)()); 
    *Other Stuff* 
}; 

window.cpp:

///Find the object of that id and set the fuction to it 
template <class R1> void WindowMain::SetButtonFunction_NoArgs(string id, R1(*func)()) { 
    for (int i = 0; i < objects_.size(); i++) { 
     if (objects_[i].getId() == id) { 
      objects_[i]->AddButton_NoArgs<R1>(func); 
     } 
    } 
} 

的问题是在这里我想,但我可以找不到它...当我尝试编译它给我这个:

1>main.obj : error LNK2019: unresolved external symbol "public: void __cdecl WindowMain::SetButtonFunction_NoArgs<int>(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,int (__cdecl*)(void))" ([email protected]@[email protected]@[email protected][email protected]@[email protected]@[email protected]@[email protected]@[email protected]@[email protected]) referenced in function "void __cdecl Create(void)" ([email protected]@YAXXZ) 

感谢您的帮助!

+0

看看std :: function和lambdas或std :: bind! –

回答

-2

模板方法必须在头文件中定义。如果它不是模板,你可以将定义移动到.cpp文件(你可能想包括window.h)

+1

_“模板方法必须在头文件中定义”_ - 这是错误的,并没有考虑显式模板实例。 –