入力用と出力用の 2 つの列挙子を格納する基本クラスがあります。どちらも静的な 2 つのメンバー関数があります。最初の関数は、入力に基づいて値を返す単なる静的関数です。constexpr 値を返す constexpr 関数テンプレートである 2 番目の関数を呼び出します。ここでクラス全体を見ることができます。
class Foo {
public:
enum Input {
INPUT_0 = 0,
INPUT_1,
INPUT_2
};
enum Output {
OUTPUT_0 = 123,
OUTPUT_1 = 234,
OUTPUT_2 = 345
};
static uint16_t update( uint8_t input ) {
if ( static_cast<int>(input) == INPUT_0 )
return updater<INPUT_0>();
if ( static_cast<int>(input) == INPUT_1 )
return updater<INPUT_1>();
if ( static_cast<int>(input) == INPUT_2 )
return updater<INPUT_2>();
return updater<INPUT_0>();
}
template<const uint8_t In>
static constexpr uint16_t updater() {
if constexpr( In == INPUT_0 ) {
std::cout << "Output updated to: " << OUTPUT_0 << '\n';
return OUTPUT_0;
}
if constexpr( In == INPUT_1 ) {
std::cout << "Output updated to: " << OUTPUT_1 << '\n';
return OUTPUT_1;
}
if constexpr( In == INPUT_2 ) {
std::cout << "Output updated to: " << OUTPUT_2 << '\n';
return OUTPUT_2;
}
}
};
コンパイル時に値がわかっているときに関数テンプレート自体を使用すると、次のようになります。
#include <iostream>
int main() {
auto output0 = Foo::updater<Foo::INPUT_0>();
auto output1 = Foo::updater<Foo::INPUT_1>();
auto output2 = Foo::updater<Foo::INPUT_2>();
std::cout << "\n--------------------------------\n";
std::cout << "Output0: " << output0 << '\n'
<< "Output1: " << output1 << '\n'
<< "Output2: " << output2 << '\n';
return 0;
}
私は正しい出力を得ています:
-出力-
Output updated to: 123
Output updated to: 234
Output updated to: 345
---------------------------------
Output0: 123
Output1: 234
Output2: 345
ただし、実行時に値が決定されるときに非 constexpr メンバー関数を使用しようとすると、何らかの理由で非 constexpr 関数が if ステートメント内のコードを実行できません。
#include <iostream>
int main() {
uint8_t input;
std::cout << "Please enter input value [0,2]\n";
std::cin >> input;
auto output = Foo::update( input );
std::cout << "Output: " << output << '\n';
return 0;
}
キーボードから入力した値に関係なく、、、0
または1
ifステートメント2
内のコードの実行に失敗しています。Foo::update()'s
常に の値を出力しています123
。
それが役に立ったら; を使用Visual Studio 2017 CE v15.9.4
しており、言語を に設定してコンパイルしていISO C++ Latest Draft Standard (/std:c++latest)
ます。
if statements
このコードがを true に評価できず、スコープ内でコードを呼び出す理由がわかりません。