如何在 C++20 中使用带有 consteval 的指针变量?
How do I use a pointer variable with consteval in c++20?
我想在consteval 表达式中使用指针变量。就像这样:
consteval int foo(int i) { return i * i; }
consteval int bar(int* i) { return (*i) * (*i); }
int main() {
const int const_int{8};
const int* const_int_ptr{&const_int};
constexpr int i = foo(const_int); //fine
constexpr int m = bar(const_int_ptr); // does not compile
return 0;
}
您可以see online at Godbolt bar
的代码无法编译。如何修复 bar
的代码?
首先,您只是遇到了类型错误。 bar()
接受 int*
但 const_int_ptr
是 int const*
。
一旦你解决了这个问题,为了使用指向常量表达式的指针,指针和它所指的东西也必须是常量表达式。现在这些都不是真的。如果你使指针本身 constexpr
,你会得到一个更局部化的错误:
<source>:7:38: error: '& const_int' is not a constant expression
7 | constexpr const int* const_int_ptr{&const_int};
| ^~~~~~~~~~
为了拥有它,地址必须是已知的——它必须有静态存储持续时间。这里的具体规则是[expr.const]/11:
if the value is of pointer type, it contains the address of an object with static storage duration, the address past the end of such an object ([expr.add]), the address of a non-immediate function, or a null pointer value,
您有一个指向 const_int
的指针,它没有静态存储持续时间,因此不能用于常量表达式。将 const_int
设为 static constexpr
变量,将指针本身也设为 constexpr
(并修复 bar
的签名),你就可以开始了:demo .
我想在consteval 表达式中使用指针变量。就像这样:
consteval int foo(int i) { return i * i; }
consteval int bar(int* i) { return (*i) * (*i); }
int main() {
const int const_int{8};
const int* const_int_ptr{&const_int};
constexpr int i = foo(const_int); //fine
constexpr int m = bar(const_int_ptr); // does not compile
return 0;
}
您可以see online at Godbolt bar
的代码无法编译。如何修复 bar
的代码?
首先,您只是遇到了类型错误。 bar()
接受 int*
但 const_int_ptr
是 int const*
。
一旦你解决了这个问题,为了使用指向常量表达式的指针,指针和它所指的东西也必须是常量表达式。现在这些都不是真的。如果你使指针本身 constexpr
,你会得到一个更局部化的错误:
<source>:7:38: error: '& const_int' is not a constant expression
7 | constexpr const int* const_int_ptr{&const_int};
| ^~~~~~~~~~
为了拥有它,地址必须是已知的——它必须有静态存储持续时间。这里的具体规则是[expr.const]/11:
if the value is of pointer type, it contains the address of an object with static storage duration, the address past the end of such an object ([expr.add]), the address of a non-immediate function, or a null pointer value,
您有一个指向 const_int
的指针,它没有静态存储持续时间,因此不能用于常量表达式。将 const_int
设为 static constexpr
变量,将指针本身也设为 constexpr
(并修复 bar
的签名),你就可以开始了:demo .