是否可以使编译时求值函数返回与同一函数的运行时求值不同的类型?

问题描述 投票:0回答:1
是否有可能在编译时确定对函数(主要是 constexpr 函数)的调用是否是编译时评估的,而不是仅仅创建该函数的另一个版本(就像模板所做的那样)具有与原始运行时评估版本?怎么办?

constexpr decltype(auto) F(int n) { if consteval { return (int)3; } else { return (char)'c'; } } int main() { int n; cin >> n; cout << typeid(decltype(F(4))).name() << endl; cout << typeid(decltype(F(n))).name() << endl; return 0; }
错误(gcc 12.2):“自动返回类型的推导不一致:‘int’然后是‘char’”

使用

if constexpr

 不会给出此错误,因为我认为它只是“删除”一段代码(如果为 false,则删除“if”部分,否则删除“else”部分)。但为什么 
if consteval
 不做同样的事情呢?
还有其他方法可以做到这一点吗?

c++ constexpr consteval
1个回答
0
投票
不,这是不可能的。

consteval

 if 语句(除了对 
consteval
 函数调用的影响之外)本质上等同于:

if (std::is_constant_evaluated()) // if consteval if (!std::is_constant_evaluated())) // if !consteval

constexpr

 if 语句可以影响返回类型推导的原因是它们将 false 分支变成了
discarded statements,使之就好像您根本没有编写该代码一样。

A

consteval

 if 语句根本不会执行两个分支之一,就像常规 if 语句一样。

© www.soinside.com 2019 - 2024. All rights reserved.