gpt4 book ai didi

c++ - 如何在模板类中拆分模板友元函数的定义?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:40:43 24 4
gpt4 key购买 nike

下面的例子编译得很好,但我不知道如何在这种特殊情况下分离 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com