用于显式特化模板类中的模板函数的 C++ 语法?
我的代码在 VC9(Microsoft Visual C++ 2008 SP1)中有效,但在 GCC 4.2(Mac 上)中无效:
I have code which works in VC9 (Microsoft Visual C++ 2008 SP1) but not in GCC 4.2 (on Mac):
struct tag {};
template< typename T >
struct C
{
template< typename Tag >
void f( T ); // declaration only
template<>
inline void f< tag >( T ) {} // ERROR: explicit specialization in
}; // non-namespace scope 'structC<T>'
我知道 GCC 希望我将我的显式专业化转移到课程之外,但我无法弄清楚语法.有什么想法吗?
I understand that GCC would like me to move my explicit specialization outside the class but I can't figure out the syntax. Any ideas?
// the following is not correct syntax, what is?
template< typename T >
template<>
inline void C< T >::f< tag >( T ) {}
推荐答案
如果不显式特化包含类,就不能特化成员函数.
但是,您可以做的是将调用转发到部分专用类型的成员函数:
You can't specialize a member function without explicitly specializing the containing class.
What you can do however is forward calls to a member function of a partially specialized type:
template<class T, class Tag>
struct helper {
static void f(T);
};
template<class T>
struct helper<T, tag1> {
static void f(T) {}
};
template<class T>
struct C {
// ...
template<class Tag>
void foo(T t) {
helper<T, Tag>::f(t);
}
};
相关文章