专门化模板类的模板成员函数? [英] Specializing a template member function of a template class?

查看:142
本文介绍了专门化模板类的模板成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板类,它有一个模板成员函数,需要被专门化,如:

I have a template class that has a template member function that needs to be specialized, as in:

template <typename T>
class X
{
public:
    template <typename U>
    void Y() {}

    template <>
    void Y<int>() {}
};

Altough VC正确处理这个错误,这不是标准的,GCC抱怨:非命名空间作用域中的显式专门化'类X< T>'

Altough VC handles this correctly, apperantly this isn't standard and GCC complains: explicit specialization in non-namespace scope 'class X<T>'

我试过:

template <typename T>
class X
{
public:
    template <typename U>
    void Y() {}
};

template <typename T>
// Also tried `template<>` here
void X<T>::Y<int>() {}

但是这会导致VC和GCC都抱怨。

But this causes both VC and GCC to complain.

这是什么正确的方法?

推荐答案

很常见的问题。一种解决方法是通过重载

Very common problem. One way to solve it is through overloading

template <typename T>
struct type2type { typedef T type; };

template <typename T>
class X
{
public:
    template <typename U>
    void Y() { Y(type2type<U>()); }

private:
    template<typename U>
    void Y(type2type<U>) { }

    void Y(type2type<int>) { }
};

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

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