下面这段代码取自folly,使用模板技术在编译时判断一个数字是否大于另一个,在GCC4.8.2下面编译没有问题,但是在Visual C++ 2013下面却无法通过,这是为什么?
#include <limits>
#include <type_traits>
#include <iostream>
template <typename RHS, RHS rhs, typename LHS>
bool greater_than_impl(
typename std::enable_if<
(rhs <= std::numeric_limits<LHS>::max()
&& rhs >= std::numeric_limits<LHS>::min()),
LHS
>::type const lhs
) {
return lhs > rhs;
}
template <typename RHS, RHS rhs, typename LHS>
bool greater_than_impl(
typename std::enable_if<
(rhs > std::numeric_limits<LHS>::max()),
LHS
> ::type const
) {
return false;
}
template <typename RHS, RHS rhs, typename LHS>
bool greater_than_impl(
typename std::enable_if <
(rhs < std::numeric_limits<LHS>::min()),
LHS
>::type const
) {
return true;
}
template <typename RHS, RHS rhs, typename LHS>
bool greater_than(LHS const lhs) {
return greater_than_impl<
RHS, rhs, typename std::remove_reference<LHS>::type
>(lhs);
}
int main(int argc, char* argv[])
{
auto v = greater_than<uint8_t, 0u, uint8_t>(0u);
std::cout << v << endl;
return 0;
}
在stackoverflow上问了以后了解原因了,是因为VC2013还不支持const expr, numeric_limit的值无法在编译期获得。
参考这里:http://stackoverflow.com/questions/22003408/c-11-stdenable-if-overloading-in-visual-c-2013