【发布时间】:2011-10-01 10:37:08
【问题描述】:
template<typename T>
struct A
{
A<T> operator%( const T& x);
};
template<typename T>
A<T> A<T>::operator%( const T& x ) { ... }
我如何使用 enable_if 对任何浮点类型 (is_floating_point) 进行以下特化?
template<>
A<float> A<float>::operator%( const float& x ) { ... }
编辑: 这是我想出的答案,与下面发布的答案不同...
template<typename T>
struct A
{
T x;
A( const T& _x ) : x(_x) {}
template<typename Q>
typename std::enable_if<std::is_same<Q, T>::value && std::is_floating_point<Q>::value, A<T> >::type operator% ( const Q& right ) const
{
return A<T>(fmod(x, right));
}
template<typename Q>
typename std::enable_if<std::is_convertible<Q, T>::value && !std::is_floating_point<Q>::value, A<T> >::type operator% ( const Q& right ) const
{
return A<T>(x%right);
}
};
就像下面的海报所说,使用 enable_if 可能不适合这个问题(它很难阅读)
【问题讨论】:
标签: c++ boost c++11 template-specialization tr1