我有這樣的源代碼,有一個枚舉,我希望可以評估爲constexpr,但編譯器給我一個錯誤,它不是。爲什麼? 如果EventOrder是enum
或enum 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>();
}
函數參數是**從來沒有** constexpr。 – ildjarn
如果將'const'從'order'(僅僅是'EventOrder order')中取出會發生什麼? – 1201ProgramAlarm
'std :: integral_constant'是一個僞選擇。 – Jarod42