我有一个模板结构
Foo
,它定义了一个内部结构Bar
。
现在,我想重载流运算符<< for this inner struct
Bar
,但编译器似乎忽略了我的重载实现:
error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘Foo<3>::Bar’)
我的代码如下:
#include <iostream>
//////////////////////////////////////////////////////////////////////////////////////////
template<int N>
struct Foo
{
struct Bar {};
};
//////////////////////////////////////////////////////////////////////////////////////////
template<int N>
std::ostream& operator<< (std::ostream& os, const typename Foo<N>::Bar& x)
{
return os;
}
//////////////////////////////////////////////////////////////////////////////////////////
int main (int argc, char** argv)
{
Foo<3>::Bar x;
std::cout << x << std::endl;
}
我看不到(也许是明显的)错误。
问题 是否可以重载属于模板类的内部结构的运算符?
你的意思是这样的吗? 使用模板类,通常更容易在模板中声明友元重载(此处演示:https://onlinegdb.com/NqTLD6_tU)
#include <iostream>
template<int N>
struct Foo
{
struct Bar
{
int x{N};
};
// friend if you need access to a private member
friend std::ostream& operator<<(std::ostream& os, const Foo<N>::Bar& bar)
{
os << bar.x;
return os;
}
private:
Bar b;
};
int main (int argc, char** argv)
{
Foo<3>::Bar x;
std::cout << x << "\n";
}