jwf*_*arn 43 c++ gcc templates
我的代码适用于VC9(Microsoft Visual C++ 2008 SP1)但不适用于GCC 4.2(在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>'
Run Code Online (Sandbox Code Playgroud)
我知道GCC希望我在课外移动我的显式专业,但我无法弄清楚语法.有任何想法吗?
// the following is not correct syntax, what is?
template< typename T >
template<>
inline void C< T >::f< tag >( T ) {}
Run Code Online (Sandbox Code Playgroud)
Geo*_*che 36
如果没有明确地专门化包含类,则无法专门化成员函数.
但是你可以做的是向部分专用类型的成员函数的前向调用:
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);
}
};
Run Code Online (Sandbox Code Playgroud)
海湾合作委员会在这里是明确的.MSVC具有非标准扩展,允许进行类内专业化.但是,标准说:
14.7.3.2:2
.显式专门化应在模板所属的名称空间中声明,或者,对于成员模板,在封闭类或封闭类模板所属的名称空间中声明.应该在类模板所属的名称空间中声明类模板的成员函数,成员类或静态数据成员的显式特化.
此外,您不能部分专门化功能.(虽然我不确定你案件中的细节,但那将是最后一击.)
你可以这样做:
#include <iostream>
struct true_type {};
struct false_type {};
template <typename T, typename U>
struct is_same : false_type
{
static const bool value = false;
};
template <typename T>
struct is_same<T, T> : true_type
{
static const bool value = true;
};
struct tag1 {};
struct tag2 {};
template< typename T >
struct C
{
typedef T t_type;
template< typename Tag >
void foo( t_type pX)
{
foo_detail( pX, is_same<Tag, tag1>() );
}
private:
void foo_detail( t_type, const true_type& )
{
std::cout << "In tag1 version." << std::endl;
}
void foo_detail( t_type, const false_type& )
{
std::cout << "In not tag1 version." << std::endl;
}
};
int main(void)
{
C<int> c;
c.foo<tag1>(int());
c.foo<tag2>(int());
c.foo<double>(int());
}
Run Code Online (Sandbox Code Playgroud)
虽然这有点难看.
| 归档时间: |
|
| 查看次数: |
20485 次 |
| 最近记录: |