问题
I'm trying to overload the ostream operator to allow output for a nested class inside a template. However, the compiler is unable to bind the actual function call to my overload.
template <class T>
struct foo
{
struct bar { };
};
template <class T>
std::ostream& operator << (std::ostream& os,
const typename foo<T>::bar& b)
{
return os;
}
int main()
{
foo<int>::bar b;
std::cout << b << std::endl; // fails to compile
}
This will compile if I define the overload as an inline friend
function:
template <class T>
struct foo
{
struct bar
{
friend std::ostream& operator << (std::ostream& os, const bar& b)
{
return os;
}
};
};
But I'd rather define the overload outside of the class. Is this possible?
回答1:
No. :-) You have already answered your own question, but somehow you don't like the answer? Johannes links to a post that explains that the inner class is a "non-deduced context". If there are some specializations of the foo template, there might be several foos with the same inner bar class. The compiler can then not figure out what foo::bar is, unless it instantiated foo for all possible Ts. The standard says that it doesn't have to do that.
What's wrong with your original solution with a friend operator? You don't have to define it inline, you just have to declare it inside the local class.
来源:https://stackoverflow.com/questions/4351567/output-a-nested-class-inside-a-template