【发布时间】:2015-10-14 22:37:07
【问题描述】:
为了支持可移植性,我想根据 size_t 是 32 位还是 64 位这一事实来选择一个常量。
代码:
using namespace std;
namespace detail {
template<enable_if<is_same<size_t, uint32_t>::value,void*>::type = nullptr>
constexpr static const size_t defaultSizeHelper() {
return ( (size_t) 1 << 30 ) / 2 * 5; //2,5 Gb
}
template<enable_if<is_same<size_t, uint64_t>::value,void*>::type = nullptr>
constexpr size_t defaultSizeHelper() {
return numeric_limits<size_t>::max() / 2;
}
}
constexpr static size_t defaultSize = detail::defaultSizeHelper();
由于error: 'std::enable_if<false, void*>::type' has not been declared. template<enable_if<is_same<size_t, uint64_t>::value,void*>::type = nullptr>,此代码无法编译
编译器 - GCC 4.9
在我看来,编译器没有将 SFINAE 原则应用于constexpr。那我该怎么办?
【问题讨论】:
-
还有可能使用标签调度,这对于您的使用示例来说会更加优雅。
defaultSizeHelper(std::integral_constant<std::size_t, sizeof(std::size_t)>{}) -
只是对我之前评论的一个小补充,您的代码在使用标签调度时将如下所示:coliru.stacked-crooked.com/a/ee0738c2369e03ec。
标签: c++ templates c++11 constexpr enable-if