我有一个基本类,它包含两个枚举数,一个用于输入,一个用于输出。它有两个成员函数,它们都是静态的。第一个函数只是一个基于输入返回值的静态函数。它将调用第二个函数,该函数是返回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
但是,当我尝试在运行时确定值时使用non-constexpr成员函数时,由于某种原因,non-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
设置为true并在其范围内调用代码。