模板化 class 和模板化方法的模板专门化语法

Template specialization syntax for templated class and templated method

我在处理 class 定义之外的模板特化的 C++ 语法时遇到了麻烦。我有这个 class:

template <class T>
class Foo     {
public:
    template <int U> 
    std::string bar();
private: 
    T m_data;
};

我如何为任何 T 和特定的 U 专门化 bar()

我期待:

template <class T> template <>
std::string Foo<T>::bar<1>() {
    return m_data.one;
}

但我得到:

error: invalid explicit specialization before ‘>’ token
template <class T> template <>
                             ^
error: enclosing class templates are not explicitly specialized

我也可以试试:

template <class T> template <int>
std::string Foo<T>::bar<1>() {
    return m_data.one;
}

但后来我得到:

error: non-class, non-variable partial specialization ‘bar<1>’ is not allowed
 std::string Foo<T>::bar<1>() {
                            ^

基于this answer

template <typename T>
class has_one
{
    template <typename C> static char test(decltype(&C::one));
    template <typename C> static long test(...);

public:
    enum { value = sizeof(test<T>(0)) == sizeof(char) };
}; 

template <class T>
class Foo {
public:
    template <int U>
    enable_if_t<U != 1 || U == 1 && has_one<T>::value, std::string> bar() {
        return m_data.one;
    }

private:
    T m_data;
};

struct Tone { std::string one; };
int main()
{
    Foo<int> f;
    f.bar<1>(); // This causes compile-time error
    Foo<Tone> f2;
    f2.bar<2>();
}