例えば、私が列挙列挙型の次の項目の計算時間を計算しますか?
enum Option
{
A = 0, B = 1, C = 2
};
を持っていると私は、結果の横にそのコンパイル時間を取得したい、すなわちnextOf<A> = B, nextOf<B> = C, nextOf<C> = A
、どのように私はそれを実装していますか?
例えば、私が列挙列挙型の次の項目の計算時間を計算しますか?
enum Option
{
A = 0, B = 1, C = 2
};
を持っていると私は、結果の横にそのコンパイル時間を取得したい、すなわちnextOf<A> = B, nextOf<B> = C, nextOf<C> = A
、どのように私はそれを実装していますか?
constexpr
を使用すると、コンパイル時の関数を記述できます。
#include <iostream>
enum Option
{
A = 0, B = 1, C = 2
};
constexpr Option nextOf(const Option option){
switch (option){
case A: return B;
case B: return C;
}
return A;
}
int main(){
constexpr Option next = nextOf(A);
}
もう1つのアプローチは、構造の部分的な特殊化を使用することです。一例として、
:
enum Option { A = 0, B = 1, C = 2 };
template<Option>
struct next;
template<> struct next<A> { static constexpr Option value = B; };
template<> struct next<B> { static constexpr Option value = C; };
template<> struct next<C> { static constexpr Option value = A; };
template<Option O>
constexpr Option next_v = next<O>::value;
int main(){
constexpr Option next = next_v<A>;
static_assert(next_v<B> == C, "!");
}
enum
sが変装して整数であるので、あなたは、単に
contexpr Option next(Option u)
{
return (Option(int(u)+1);
}
またはコースこれは、未定義の動作として(C)次聞かせを定義することができます。次の(C)は例外をスロー、(INT-S上の典型的なラップaroud算術)
return (Option((int(u)+1)%3);
又は入力にフィルタを=ように代替は、%3の結果とすることができるが、それはなりますフィクションはもはやconsterxpr
です。
'myEnum + 1'はうまくいかないのですか? –
ステートマシンを実装しますか? – SHR