模板类中模板函数的显式专门化的C ++语法? [英] C++ syntax for explicit specialization of a template function in a template class?

查看:101
本文介绍了模板类中模板函数的显式专门化的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 ) {}


推荐答案

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);
    }
};

这篇关于模板类中模板函数的显式专门化的C ++语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆