模板化类和模板化方法的模板专用化语法

Template specialization syntax for templated class and templated method

本文关键字:专用 语法 方法      更新时间:2023-10-16

我在类定义之外的模板专用化中遇到C++语法时遇到麻烦。 我有这个类:

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

我怎样才能专注于任何T和特定Ubar()

我期待:

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>() {
^

基于这个答案:

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>();
}