C++ C++;11 std::在Visual C+中重载时启用"U"+;2013
以下代码片段取自,用于检查编译时一个整数是否大于另一个整数C++ C++;11 std::在Visual C+中重载时启用"U"+;2013,c++,c++11,sfinae,C++,C++11,Sfinae,以下代码片段取自,用于检查编译时一个整数是否大于另一个整数 #include <limits> #include <type_traits> template <typename RHS, RHS rhs, typename LHS> bool greater_than_impl( typename std::enable_if< (rhs <= std::numeric_limits<LHS>::max()
#include <limits>
#include <type_traits>
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 test()
{
auto v = greater_than<int, 0, int>(0);
std::cout << v << std::endl;
return 0;
}
#包括
#包括
模板
bool大于impl(
typename std::启用\u如果<
(rhs=std::数值限制::min()),
LHS
>::类型const lhs
) {
返回左侧>右侧;
}
模板
bool大于impl(
typename std::启用\u如果<
(rhs>std::数值限制::max()),
LHS
>::type const
) {
返回false;
}
模板
bool大于impl(
typename std::启用\u如果<
(rhs::type const
) {
返回true;
}
模板
bool大于(左侧常量左侧){
返回大于实际值的值<
RHS,RHS,typename std::remove_reference::type
>(lhs);
}
int测试()
{
自动v=大于(0);
std::cout不支持constexpr。根据我所知,它是非const静态
函数。您不能在需要常量表达式的地方使用它们,例如:
#include <limits>
#include <array>
int main()
{
std::array<int, std::numeric_limits<int>::max()> a;
}
error C2975: '_Size' : invalid template argument for 'std::array', expected compile-time constant expression
不幸的是,这会导致相同的函数模板重新定义错误。您可以直接使用INT_MAX
和INT_MIN
,但这需要专门化16种类型(对于libstdc++)最好完全避免使用这种方法,并遵循建议。在问题中包含有关错误的附加信息将非常有用。错误出现在哪行?它给出的确切错误文本是什么?我只能找到相关的错误报告:这需要constexpr
用于数值\u limits::max()和最小值()
,VS2013没有。如果你安装最新的CTP,它可能会起作用,我相信这会增加一些constexpr
支持,但即使这样,他们也不太可能更新stdlib。但我不明白在任何情况下都需要这样做;如果你有constexpr
支持,为什么不直接实现它呢?另外,C++14还增加了constexpr
到
struct wrapper_base
{
// member variables
};
template <typename T>
struct wrapper : public wrapper_base
{
static const T max()
{
return T();
}
static const T min()
{
return T();
}
};
template <>
struct wrapper<int>
{
static const int max()
{
return INT_MAX;
}
static const int min()
{
return INT_MIN;
}
};