【发布时间】:2016-07-14 14:08:34
【问题描述】:
几天来我一直在努力解决这个问题,查找它并在开源项目中寻找类似的代码:无法真正找到我做错了什么。
基本上,鉴于下面的代码(提炼其本质):
#include <iostream>
using std::cout;
using std::endl;
using std::string;
template <typename T>
class Node {
T value_;
public:
Node(const T& value) : value_(value) {}
T const value() const { return value_; }
friend
std::ostream& operator <<(std::ostream& out, const Node<T>& node);
Node<T> operator +(const Node<T>& other) {
return Node(value() + other.value());
}
};
template <typename T>
std::ostream& operator <<(std::ostream& out, const Node<T>& node) {
return out << node.value();
}
在这样的代码中使用时:
int main(int argc, char* argv[]) {
Node<string> node("node X");
cout << node << endl;
Node<int> three(3);
cout << three << endl;
return EXIT_SUCCESS;
}
我收到以下链接器错误:
Undefined symbols for architecture x86_64:
"operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, Node<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > const&)", referenced from:
_main in StlPractice.cpp.o
"operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, Node<int> const&)", referenced from:
_main in StlPractice.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
据我所知,以上都是合法的 C++11 代码;模板定义明确,但它似乎以某种方式逃脱了链接器找到它的能力。
这是在 OS X 上使用 cmake 构建的:
cmake_minimum_required(VERSION 3.3)
project(simple_template)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES src/simple_template.cpp)
add_executable(simple ${SOURCE_FILES})
什么给了?
提前致谢!
更新在问题之后,我还运行了以下相同的结果:
$ clang++ src/simple_template.cpp
Undefined symbols for architecture x86_64:
"operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, Node<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > const&)", referenced from:
_main in StlPractice-e20370.o
"operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, Node<int> const&)", referenced from:
_main in StlPractice-e20370.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
【问题讨论】:
-
是的,它可以编译,并且主要包含“通常的嫌疑人”
iostream;我正在使用 cmake - 将其添加到问题中。谢谢你的链接,我会在此期间检查一下。
标签: c++ templates c++11 operator-overloading friend