2017-07-01 76 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

_「模板方法必須在頭文件中定義」_ - 這是錯誤的,並沒有考慮顯式模板實例。 –