我正在构建一些输入检查器,它需要具有整数和/或双精度的特定函数(例如,isPrime"应该仅适用于整数).
I'm building some input checker that needs to have specific functions for integer and/or double (for example 'isPrime' should only be available for integers).
如果我使用 enable_if
作为参数,它运行良好:
If I'm using enable_if
as a parameter it's working perfectly :
template <class T>
class check
{
public:
template< class U = T>
inline static U readVal(typename std::enable_if<std::is_same<U, int>::value >::type* = 0)
{
return BuffCheck.getInt();
}
template< class U = T>
inline static U readVal(typename std::enable_if<std::is_same<U, double>::value >::type* = 0)
{
return BuffCheck.getDouble();
}
};
但是如果我将它用作模板参数(如 http://en.cppreference.com/w/cpp/types/enable_if )
but if I'm using it as a template paramater (as demonstrated on http://en.cppreference.com/w/cpp/types/enable_if )
template <class T>
class check
{
public:
template< class U = T, class = typename std::enable_if<std::is_same<U, int>::value>::type >
inline static U readVal()
{
return BuffCheck.getInt();
}
template< class U = T, class = typename std::enable_if<std::is_same<U, double>::value>::type >
inline static U readVal()
{
return BuffCheck.getDouble();
}
};
然后我有以下错误:
error: ‘template<class T> template<class U, class> static U check::readVal()’ cannot be overloaded
error: with ‘template<class T> template<class U, class> static U check::readVal()’
我不知道第二个版本有什么问题.
I can't figure out what is wrong in the second version.
默认模板参数不是模板签名的一部分(因此两个定义都尝试定义相同的模板两次).然而,它们的参数类型是签名的一部分.所以你可以这样做
Default template arguments are not part of the signature of a template (so both definitions try to define the same template twice). Their parameter types are part of the signature, however. So you can do
template <class T>
class check
{
public:
template< class U = T,
typename std::enable_if<std::is_same<U, int>::value, int>::type = 0>
inline static U readVal()
{
return BuffCheck.getInt();
}
template< class U = T,
typename std::enable_if<std::is_same<U, double>::value, int>::type = 0>
inline static U readVal()
{
return BuffCheck.getDouble();
}
};
这篇关于std::enable_if :参数与模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!