是否可以为模板类的成员函数编写专门化?

Mih*_*yan 3 c++ templates

template <class T, bool flag>
class A
{
    //...
    void f()
    {
        std::cout << "false" << std::endl;
    }
    //...
};

template<class T>
void A<T, true>::f<T, true>()
{
    std::cout << "true" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码是错误的,不编译,但你知道我将要做什么.那我该怎么做呢?

Mar*_*k B 5

你不能只专门化一个类的方法.通常你可以用模板嵌套类来解决这个问题T.

template <class T, bool flag>
class A
{
    //...
    template <class Q, bool flag>
    class F_Helper
    {
        void operator()()
        {
            std::cout << "false" << std::endl;
        }
    };

    template <class Q>
    class F_Helper<Q, true>
    {
        void operator()()
        {
            std::cout << "true" << std::endl;
        }
    };

    F_Helper<T> f;
    //...
};
Run Code Online (Sandbox Code Playgroud)

显然,如果您确实需要访问封闭类的this指针,则需要更多的样板.