[英]Overloading of a non-member operator for a templated inner class
我无法弄清楚为什么编译器无法看到或使用operator<< ( std::ostream & os, typename A<T>::B const& b )
。
#include <vector>
#include <iostream>
template <typename T>
struct A
{
struct B
{
std::vector<T> innervec;
};
std::vector<B> outervec;
};
template <typename T>
auto operator<< ( std::ostream & os, typename A<T>::B const& b ) -> std::ostream&
{
for (auto e : b.innvervec)
os << "\n\t" << e;
return os;
}
template <typename T>
auto operator<< ( std::ostream & os, A<T> const& a ) -> std::ostream&
{
for (auto e : a.outervec)
os << '\n' << e;
return os;
}
int main()
{
A<int> a;
A<int>::B b1;
A<int>::B b2;
b1.innervec.push_back( 11 );
b1.innervec.push_back( 12 );
b2.innervec.push_back( 21 );
b2.innervec.push_back( 22 );
a.outervec.push_back( b1 );
a.outervec.push_back( b2 );
std::cout << a << std::endl;
}
在VC ++ 15上给出了以下错误:
error C2679: binary '<<': no operator found which takes a right-hand operand of type 'A<int>::B' (or there is no acceptable conversion)
并且它也不能在GCC上编译(尽管只在在线编译器中尝试过)。
我想有一个关于范围和演绎的规则,但我无法确切地找出。
错误是因为嵌套类型的重载包含非推导的上下文参数typename A<T>::B const& b
,对于不能提供显式模板参数T
的运算符,您需要将运算符定义为嵌套的A<T>::B
为:
template <typename T>
struct A
{
struct B
{
std::vector<T> innervec;
friend auto operator<< ( std::ostream & os, B const& b ) -> std::ostream&
{
for (auto e : b.innervec)
os << "\n\t" << e;
return os;
}
};
std::vector<B> outervec;
};
有问题的部分是参数列表中的A<T>::B
,因为编译器不能推导出这种形式的类型表达式,因为成员B
存在和类型依赖于T
我会直接将b
参数的类型作为模板参数T
,并使用SFINAE来约束已接受的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.