gpt4 book ai didi

c++ - 为什么引用不能与编译时函数一起使用?

转载 作者:行者123 更新时间:2023-11-30 00:43:58 24 4
gpt4 key购买 nike

我有两个片段。

第一个片段:

#include <string>

template <typename T>
constexpr bool foo(T&&) {
return false;
}

int main() {
std::string a;
if constexpr (foo(a)) {
}
}

第二个片段:

#include <string>

template <typename T>
constexpr bool foo(T&&) {
return false;
}

int main() {
std::string a;
std::string& x = a;
if constexpr (foo(x)) {
}
}

第一个编译通过,但第二个编译不通过(错误信息:错误:'x'的值在常量表达式中不可用。为什么?为什么a 可用于常量表达式而 x 不是?

该命令,用于编译g++ -std=c++17 main.cpp

最佳答案

因为常量表达式通常无法评估引用具有自动存储持续时间的对象的引用。在这里,我的意思是通过确定 identity 来“评估”对象的值,不是通过确定对象的值。因此,即使您的示例中不需要对象 a 的值(即没有应用左值到右值的转换),foo(x) 仍然不是常量表达。

注意 foo(a) 不计算任何引用。虽然 foo 的参数是一个引用,但它不会作为表达式求值。其实就算评价了,比如,

template <typename T>
constexpr bool foo(T&& t) {
t;
return false;
}

foo(a) 仍然是一个常量表达式。这种情况是异常(exception),因为引用 t 是在 foo(a) 的评估中初始化的。


标准中的相关部分(不相关的部分我删掉了):

[expr.const]/2 :

An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:

  • ...

  • an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either

    • it is initialized with a constant expression or

    • its lifetime began within the evaluation of e;

  • ...

[expr.const]/6 :

A constant expression is either a glvalue core constant expression that refers to an entity that is a permitted result of a constant expression (as defined below), ... An entity is a permitted result of a constant expression if it is an object with static storage duration that is either not a temporary object or is a temporary object whose value satisfies the above constraints, or it is a function.

关于c++ - 为什么引用不能与编译时函数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51456712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com