C++ 来自模板函数(C+;+;)的未定义引用
使用C++ 来自模板函数(C+;+;)的未定义引用,c++,templates,undefined,linker-errors,definition,C++,Templates,Undefined,Linker Errors,Definition,使用foo.hpp: g++ -c *.cpp && g++ *.o -o foo #ifndef FOO_H_ #define FOO_H_ template<typename T> class Foo { private: T ft_; public: Foo(const T & ft) : ft_(ft) { } Foo display(T x); }; #endif #include "foo.hpp" #inc
foo.hpp
:
g++ -c *.cpp && g++ *.o -o foo
#ifndef FOO_H_
#define FOO_H_
template<typename T>
class Foo {
private:
T ft_;
public:
Foo(const T & ft) : ft_(ft) { }
Foo display(T x);
};
#endif
#include "foo.hpp"
#include<iostream>
using namespace std;
template<typename T>
Foo<T> Foo<T>::display(T x) {
// do some stuff - not too relevant
cout << "[" << x << "]";
Foo<T> res(x);
return res;
}
和main.cpp
:
g++ -c *.cpp && g++ *.o -o foo
#ifndef FOO_H_
#define FOO_H_
template<typename T>
class Foo {
private:
T ft_;
public:
Foo(const T & ft) : ft_(ft) { }
Foo display(T x);
};
#endif
#include "foo.hpp"
#include<iostream>
using namespace std;
template<typename T>
Foo<T> Foo<T>::display(T x) {
// do some stuff - not too relevant
cout << "[" << x << "]";
Foo<T> res(x);
return res;
}
#包括
#包括“foo.hpp”
使用名称空间std;
int main(){
傅f(42),;
Foo g=f.display(39);
返回0;
}
为什么
#ifndef FOO_H_
#define FOO_H_
template<typename T>
class Foo {
private:
T ft_;
public:
Foo(const T & ft) : ft_(ft) { }
Foo display(T x);
};
#endif
PS使用内联函数定义。每当函数的声明和定义被分成两个文件时,就会出现问题在C++中,你需要把模板化方法和函数的定义放在头文件中。你忘记读C++书中的页,它告诉你不要在<代码> .CPP < /C>文件中定义函数模板。参见,C++中的11个?@ Lealness CraceSeEnrimeHMM,我似乎已经对外部模板感到困惑…我认为有人提议可以在
.cpp
文件中定义模板,并认为它已经被引入。将其从答案中删除。也许您正在考虑导出,它实际上已从C++11中删除,但无论如何都不起作用。ThanX!这让我困惑,因为我看到它在我的C++书籍中使用过这种方式…
#ifndef FOO_H_
#define FOO_H_
template<typename T>
class Foo {
private:
T ft_;
public:
Foo(const T & ft) : ft_(ft) { }
Foo display(T x);
};
#endif