[英]Generic ostream issue in C++
我尝试做一个通用向量,但是当我编译它时会抛出这个错误:
Undefined symbols for architecture x86_64:
"operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, Vec2<int> const&)", referenced from:
referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
请有人可以帮助我。 这是代码:
#include <iostream>
template<typename T>
class Vec2 {
public:
Vec2(T x, T y):x(x), y(y) {}
friend std::ostream &operator <<(std::ostream &, const Vec2<T> &);
private:
T x;
T y;
};
template<typename T>
std::ostream &operator << (std::ostream &os, const Vec2<T> &vec) {
os << "x: " << vec.x << ", y: " << vec.y << std::endl;
return os;
}
int main(int argc, const char * argv[]) {
Vec2<int> vi(3, 4);
//Vec2<float> vf(3, 4);
std::cout << vi;
//std::cout << vf;
return 0;
}
当我不使用模板时,代码有效。
我收到警告:
main.cpp:7:66: warning: friend declaration 'std::ostream& operator<<(std::ostream&, const Vec2<T>&)' declares a non-template function [-Wnon-template-friend]
friend std::ostream &operator <<(std::ostream &, const Vec2 &);
^
main.cpp:7:66: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)
您将非模板operator<<
声明为朋友。 您应该将您定义的函数模板声明为友元:
template<typename U>
friend std::ostream &operator <<(std::ostream &, const Vec2<U> &);
最简单的方法是声明函数inline
template<typename T>
class Vec2 {
public:
Vec2(T x, T y):x(x), y(y) {}
friend std::ostream& operator <<(std::ostream& os, const Vec2 &vec)
{
return os << "x: " << vec.x << ", y: " << vec.y << std::endl;
}
private:
T x;
T y;
};
否则,您必须在之前声明模板函数:
template <typename T> class Vec2;
template <typename T>
std::ostream& operator <<(std::ostream& os, const Vec2<T>& vec);
template<typename T>
class Vec2 {
public:
Vec2(T x, T y):x(x), y(y) {}
#if 0
// Here all operator << <U> are friend
template <typename U>
friend std::ostream& operator <<(std::ostream& os, const Vec2<U> &vec);
#else
// Here only the matching specialization is friend
friend std::ostream& operator << <>(std::ostream& os, const Vec2& vec);
#endif
private:
T x;
T y;
};
template <typename T>
std::ostream& operator <<(std::ostream& os, const Vec2<T>& vec)
{
return os << "x: " << vec.x << ", y: " << vec.y << std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.