如何在模板类中专门化模板成员函数(已指定)

How to specialize template member functions in template class (already specilzied)?

本文关键字:函数 专门化 成员      更新时间:2023-10-16

例如:

template<unsigned number>
struct A
{
    template<class T>
    static void Fun()
    {}
};
template<>
struct A<1>
{
    template<class T>
    static void Fun()
    {
       /* some code here. */
    }
};

并且想要专门化A<1> ::函数()

template<>
template<>
void A<1>::Fun<int>()
{
    /* some code here. */
}

似乎不起作用。怎么做?谢谢

类模板的显式专用化类似于常规类(它是完全实例化的,因此不是参数类型)。因此,您不需要外部template<>:

// template<> <== NOT NEEDED: A<1> is just like a regular class
template<> // <== NEEDED to explicitly specialize member function template Fun()
void A<1>::Fun<int>()
{
    /* some code here. */
}

类似地,如果您的成员函数Fun不是一个函数模板,而是一个常规成员函数,那么您根本不需要任何template<>

template<>
struct A<1>
{
    void Fun();
};
void A<1>::Fun()
{
    /* some code here. */
}