2017-08-25 31 views
0

我有这样的源代码,有一个枚举,我希望可以评估为constexpr,但编译器给我一个错误,它不是。为什么? 如果EventOrder是enumenum class,则无关紧要。Enum不是一个constexpr?

#include <limits> 
#include <type_traits> 

enum class EventOrder 
{ 
     Last = 1'000'000, 
     Default = 0, 
     Logger = -1024, 
     First = -1'000'000 
}; 

template <typename T> 
constexpr inline std::underlying_type_t<T> num(T value) { 
     static_assert(std::is_enum<T>::value, "num can only be used on enumeration types"); 
     return static_cast<std::underlying_type_t<T>>(value); 
} 

constexpr EventOrder sum(const EventOrder order, const std::underlying_type_t<EventOrder> orderDelta) 
{ 
     static_assert(order >= EventOrder::First, "Order Value out of bounds"); 
     return static_cast<EventOrder>(num(order) + orderDelta); 
} 

int main() 
{ 
     constexpr EventOrder e = EventOrder::Default; 
     sum(e, 2); 
     return 0; 
} 

它提供了错误:

$ g++ -std=c++14 EventTest.cc 
EventTest.cc: In function ‘constexpr EventOrder sum(EventOrder, std::underlying_type_t<EventOrder>)’: 
EventTest.cc:23:2: error: non-constant condition for static assertion 
    static_assert(order >= EventOrder::First, "Order Value out of bounds"); 
^
EventTest.cc:23:2: error: ‘order’ is not a constant expression 

为什么秩序是不是constexpr?

编辑1

所以传递参数作为模板变量只有解决呀?或者你知道一些不同的方式?

#include <limits> 
#include <type_traits> 

enum class EventOrder 
{ 
     Last = 1'000'000, 
     Default = 0, 
     Logger = -1024, 
     First = -1'000'000 
}; 

template <typename T> constexpr inline std::underlying_type_t<T> num(T value) 
{ 
    static_assert(std::is_enum<T>::value, "num can only be used on enumeration types"); 
    return static_cast<std::underlying_type_t<T>>(value); 
} 

template< typename T > 
constexpr bool LimitedValue(const T value, const T min, const T max) 
{ 
     return value >= min && value <= max; 
} 

template <EventOrder orderl, std::underlying_type_t<EventOrder> orderr> 
constexpr std::underlying_type_t<EventOrder> orderSum() 
{ 
     return num(orderl) + orderr; 
} 

template <EventOrder orderl, std::underlying_type_t<EventOrder> orderr> 
constexpr EventOrder order() 
{ 
     static_assert(LimitedValue(orderSum<orderl, orderr>(), num(EventOrder::First), num(EventOrder::Last)), "order out of baunds"); 
     return static_cast<EventOrder>(orderSum<orderl, orderr>()); 
} 

int main() 
{ 
     EventOrder e = order<EventOrder::Default, 2>(); 

} 
+2

函数参数是**从来没有** constexpr。 – ildjarn

+0

如果将'const'从'order'(仅仅是'EventOrder order')中取出会发生什么? – 1201ProgramAlarm

+1

'std :: integral_constant'是一个伪选择。 – Jarod42

回答

2

即使功能是constexpr功能,它仍然可以用非const参数调用。因此,当编译器处理该函数时,它不知道order的值,并且不能在static_assert中使用它。

+2

如果'main'中的变量是constexpr,则无关紧要。 ; - ] – ildjarn

+0

@ildjarn,谢谢你指出错误。 –

相关问题