关于c ++:模板化类和模板化方法的模板专业化语法

Template specialization syntax for templated class and templated method

本问题已经有最佳答案,请猛点这里访问。

我在类定义之外的模板专门化的C ++语法问题上遇到了麻烦。 我有这个课:

1
2
3
4
5
6
7
8
template <class T>
class Foo     {
public:
    template <int U>
    std::string bar();
private:
    T m_data;
};

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

我期待:

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

但是我得到:

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

我也可以尝试:

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

但是我得到:

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


基于此答案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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>();
}