作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
下面的例子编译得很好,但我不知道如何在这种特殊情况下分离 operator<<() 的声明和定义。
每次我尝试拆分定义时, friend 都会造成麻烦,而 gcc 会提示 operator<<() 定义必须恰好采用一个参数。
#include <iostream>
template <typename T>
class Test {
public:
Test(const T& value) : value_(value) {}
template <typename STREAM>
friend STREAM& operator<<(STREAM& os, const Test<T>& rhs) {
os << rhs.value_;
return os;
}
private:
T value_;
};
int main() {
std::cout << Test<int>(5) << std::endl;
}
Operator<<() 应该有一个自由的第一个参数来处理不同类型的输出流(std::cout、std::wcout 或 boost::asio::ip::tcp::iostream)。第二个参数应该绑定(bind)到周围类的特殊版本。
Test<int> x;
some_other_class y;
std::cout << x; // works
boost::asio::ip::tcp::iostream << x; // works
std::cout << y; // doesn't work
boost::asio::ip::tcp::iostream << y; // works
此外,使用非成员函数并不等同于拆分定义和声明,因为非成员函数无法访问类的私有(private)属性。
最佳答案
最简单的可能是让所有这些模板操作符成为 friend :
#include <iostream>
template <typename T>
class Test
{
public:
Test(const T& value) : value_(value) {}
template <typename STREAM, typename U>
friend STREAM& operator<<(STREAM& os, const Test<U>& rhs);
private:
T value_;
};
template <typename STREAM, typename T>
STREAM& operator<<( STREAM& os, const Test<T>& rhs )
{
os << rhs.value_;
return os;
}
关于c++ - 如何在模板类中拆分模板友元函数的定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2819994/
我是一名优秀的程序员,十分优秀!