小编Kis*_*kla的帖子

使用 SFINAE 检查函数是否为 constexpr

我想检查一个函数是否可以在编译期间被评估。我发现了这个,但我不完全理解这个概念。我有几个疑问:

  1. 代码中下面这行的作用是什么?
    template<int Value = Trait::f()>

  2. 每次当我需要检查该函数是否可以在编译时评估时,是否需要将其设为某个结构的成员函数?

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)

c++ templates compile-time sfinae constexpr

5
推荐指数
1
解决办法
202
查看次数

为什么会编译“if constexpr”的错误分支?

为什么这段代码在编译时出错?我对“ ”的了解(以及这个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正在编译。

c++ constexpr c++17 if-constexpr

0
推荐指数
1
解决办法
232
查看次数

标签 统计

c++ ×2

constexpr ×2

c++17 ×1

compile-time ×1

if-constexpr ×1

sfinae ×1

templates ×1