我在使用C ++的类定义之外的模板特化语法时遇到了麻烦。我有这门课:
template <class T>
class Foo {
public:
template <int U>
std::string bar();
private:
T m_data;
};
如何针对任何bar()
和特定T
专门设定U
?
我在期待:
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>() {
^
答案 0 :(得分: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>();
}