小编Ale*_* R.的帖子

从constexpr模板函数调用non constexpr

我偶然在调用非constexpr功能constexpr模板功能:在下面的代码片段无法编译预期由于非constexpr的通话设置,但FOO编译.谁能告诉我foo编译的原因?

template<class T>
void set(T& x){
    x++;
}

template<class T>
constexpr void foo(T& x){
    set<T>(x);
}

constexpr void bar(int& x){
    set<int>(x);
}

void bar(){
    int x = 5;
    foo(x);
    bar(x);
}
Run Code Online (Sandbox Code Playgroud)

编译器无法编译错误:

<source>: In function 'constexpr void bar(int&)':
<source>:12:13: error: call to non-constexpr function 'void set(T&) [with T = int]'
     set<int>(x);
     ~~~~~~~~^~~
Compiler returned: 1
Run Code Online (Sandbox Code Playgroud)

编辑:附加的编译器错误和重新定义的问题.这里没有副作用.

如下面的bolov和Rekete1111所述,模板将在稍后进行评估.当不满足constexpr限制时,constexpr模板函数成为某种半constexpr函数.该-oG编译下面的代码片段显示结果,该constexpr FOO将得到优化并共同foo2的不同时俩都没有履行constexpr功能(可能是一个的后果要求直列 constexpr的含义):

template<class T>
void set(volatile T& x){
    x++; …
Run Code Online (Sandbox Code Playgroud)

c++ gcc templates constexpr c++17

6
推荐指数
1
解决办法
578
查看次数

标签 统计

c++ ×1

c++17 ×1

constexpr ×1

gcc ×1

templates ×1