2012-04-11 98 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