【发布时间】:2013-04-17 05:21:03
【问题描述】:
首选是这样的:
template<typename T>
bool isNotZero(const T &a)
{
if (std::is_floating_point<T>::value) return abs(a) > std::numeric_limits<T>::epsilon();
else return a;
}
或者这个:?
template<typename T>
std::enable_if<std::is_floating_point<T>::value, bool>::type
isNotZero(const T &a) { return abs(a) > std::numeric_limits<T>::epsilon(); }
template<typename T>
std::enable_if<std::is_integral<T>::value, bool>::type
isNotZero(const T &a) { return a; }
我通常使用第一种来避免许多版本的功能。
我相信是完全一样的。
第一个版本在操作码阶段优化,第二个版本在模板实例化阶段。
【问题讨论】:
-
我更喜欢前者,因为在这种特殊情况下更容易理解。但是,当函数的主体更复杂时,后者可能很有用。
标签: c++ templates c++11 sfinae