我有一个包含两个枚举器的基本类,一个用于输入,一个用于输出。它有两个成员函数,它们都是静态的。第一个函数只是一个静态函数,它根据输入返回一个值。它将调用第二个函数,该函数是一个将返回 constexpr 值的 constexpr 函数模板。你可以在这里看到完整的课程。
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
或2
,它都无法在Foo::update()'s
if 语句中执行代码。它总是打印出123
.
如果有帮助;我正在使用Visual Studio 2017 CE v15.9.4
并且正在编译它,语言设置为ISO C++ Latest Draft Standard (/std:c++latest)
.
我不知道为什么这段代码无法评估if statements
为真并在其范围内调用代码。