2012-04-11 63 views
0

我有一個類需要在各種不同的上下文中調用外部函數。我希望大家都能夠靈活,所以我使用的,應與仿函數,函數指針,等等。一個簡單的例子看起來像一個工作接口(由數值方法的第3版的啓發):鏈接錯誤與模板類

class MyClass { 
    public: 
    template <class T> 
    MyClass(T &f_) { f = f_; } 
    private: 
    int (*f)(int); 
}; 

int myFn(int i) { 
    return i % 100; 
} 

int main() { 
    MyClass test(myFn); 
    return 0; 
} 

到目前爲止太好了; g ++編譯這個沒有任何抱怨。在我的真實應用程序中,有更多的代碼,所以我把事情分成多個文件。例如,

test2.h:

#ifndef __test2__ 
#define __test2__ 

class MyClass { 
    public: 
    template <class T> 
    MyClass(T &f_);  
private: 
    int (*f)(int); 
}; 

#endif 

測試2.cpp:

#include "test2.h" 

template <class T> 
MyClass::MyClass(T &f_) { 
    f = f_; 
} 

main.cpp中:

#include "test2.h" 

int myFn(int i) { 
    return i % 100; 
} 

int main() { 
    MyClass test(myFn); 
    return 0; 
} 

當我嘗試編譯這個使用g++ test2.cpp main.cpp,我得到以下鏈接錯誤:

/tmp/ccX02soo.o: In function 'main': 
main.cpp:(.text+0x43): undefined reference to `MyClass::MyClass<int()(int)>(int (&)(int))' 
collect2: ld returned 1 exit status 

似乎g ++沒有意識到我也在編譯test2.cpp。有關可能會發生什麼的任何想法?

感謝,

--craig

+0

的[?爲什麼模板只能在頭文件中實現]可能重複(http://stackoverflow.com/questions/495021 /爲什麼-可以模板,只待實施合的頭文件) – 2012-04-11 11:03:36

回答

1

模板類都必須有自己的執行可見使用它們,除非他們完全有專門的所有翻譯單元。

這意味着你必須移動在頭的實現:

//test2.h 
#ifndef __test2__ 
#define __test2__ 

class MyClass { 
    public: 
    template <class T> 
    MyClass(T &f_);  
private: 
    int (*f)(int); 
}; 

template <class T> 
MyClass::MyClass(T &f_) { 
    f = f_; 
} 

#endif