请考虑以下代码:
template < typename T >
struct A
{
struct B { };
};
template < typename T >
void f( typename A<T>::B ) { }
int main()
{
A<int>::B x;
f( x ); // fails for gcc-4.1.2
f<int>( x ); // passes
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以这里gcc-4.1.2要求f明确指定模板参数.这符合标准吗?较新版本的GCC是否修复了此问题?如何避免int在调用时明确指定f?
更新: 这是一个解决方法.
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
template < typename T >
struct A
{
typedef T argument;
struct B { typedef A outer; };
};
template < …Run Code Online (Sandbox Code Playgroud) 我正在尝试重载ostream运算符以允许输出模板内的嵌套类.但是,编译器无法将实际函数调用绑定到我的重载.
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
}
Run Code Online (Sandbox Code Playgroud)
如果我将重载定义为内联friend函数,这将编译:
template <class T>
struct foo
{
struct bar
{
friend std::ostream& operator << (std::ostream& os, const bar& b)
{
return os;
}
};
};
Run Code Online (Sandbox Code Playgroud)
但我宁愿在课外定义重载.这可能吗?