链接错误:模板化的朋友操作员超载
问题描述:
我有一个奇怪的链接错误。我遵循here提供的说明来避免这种问题,但我无法弄清楚如何拆分头文件和实现文件。链接错误:模板化的朋友操作员超载
这是我的测试文件:
#include <cargo.h>
#include <iostream>
#include <string>
using namespace std;
using namespace dom;
int main()
{
dom::cargo<string> text("Hello, World!");
cout << text << endl;
return 0;
}
头文件class cargo
包含在测试:
#ifndef CARGO_H
#define CARGO_H 1
#include "node.h"
#include <iostream>
namespace dom
{
template <typename Type> class cargo;
template <typename Type>
std::ostream& operator<<(std::ostream&, const dom::cargo<Type>&);
template <typename Type>
class cargo
: public dom::node
{
Type value;
public:
cargo()
: value()
{ }
cargo(Type value)
: value(value)
{ }
friend std::ostream& operator<< <>(std::ostream&, const dom::cargo<Type>&);
};
}
#endif // !CARGO_H
及其实施:
#include "cargo.h"
template <typename Type>
std::ostream& operator<< (std::ostream& ostream, dom::cargo<Type>& cargo)
{
return (ostream << cargo.value);
}
我使用的CMake编译并将其全部链接起来。 的链接错误我得到的是有关未定义参考operator <<
:
Scanning dependencies of target test
[100%] Building CXX object Tests/CMakeFiles/test.dir/test0.c++.o
Linking CXX executable test
CMakeFiles/test.dir/test0.c++.o: In function `main':
test0.c++:(.text+0x9b): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& dom::operator<< <std::basic_string<char, std::char_traits<char>, std::allocator<char> > >(std::basic_ostream<char, std::char_traits<char> >&, dom::cargo<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > const&)'
collect2: ld returned 1 exit status
make[2]: *** [Tests/test] Error 1
make[1]: *** [Tests/CMakeFiles/test.dir/all] Error 2
make: *** [all] Error 2
我在做什么错?请帮帮我!
答
(成员)函数模板不是函数;链接器不会看到它们,除非你实例化它们。源文件是分开编译的,所以如果你把一个(成员)函数模板放在一个源文件中,并且没有明确地实例化它,链接器就不会看到它。
所以在你的情况下,函数模板还没有变成cargo.o
中的函数,所以链接器报告错误,因为main.o
依赖于它。您需要将模板放在头文件中,或者在cargo.cpp
中明确实例化它。
了解!谢谢! :) – Rizo 2010-11-04 12:29:29