我想检查一个函数是否可以在编译期间被评估。我发现了这个,但我不完全理解这个概念。我有几个疑问:
代码中下面这行的作用是什么?
template<int Value = Trait::f()>
每次当我需要检查该函数是否可以在编译时评估时,是否需要将其设为某个结构的成员函数?
PS
我复制链接中的代码,只是为了方便。
template<typename Trait>
struct test
{
template<int Value = Trait::f()>
static std::true_type do_call(int){ return std::true_type(); }
static std::false_type do_call(...){ return std::false_type(); }
static bool call(){ return do_call(0); }
};
struct trait
{
static int f(){ return 15; }
};
struct ctrait
{
static constexpr int f(){ return 20; }
};
int main()
{
std::cout << "regular: " << test<trait>::call() << std::endl;
std::cout << "constexpr: " << test<ctrait>::call() << std::endl;
}
Run Code Online (Sandbox Code Playgroud) 为什么这段代码在编译时出错?我对“ ”的了解(以及这个)if constexpr表明该else块不应该被编译。
if constexpr (true) {
int a = 10;
} else {
int b = 10
}
Run Code Online (Sandbox Code Playgroud)
错误是:
error: expected ‘,’ or ‘;’ before ‘}’ token
Run Code Online (Sandbox Code Playgroud)
使用的编译器:g++ version 7.5.0
编译时我使用了-std=c++17标志。
PS缺少的';' 是故意的,只是为了检查是否else正在编译。