2017-08-25 30 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,謝謝你指出錯誤。 –

相關問題