c++如何将constexpr值与运算符[]一起使用

c++ how to use constexpr value with operator []

本文关键字:一起 运算符 constexpr c++      更新时间:2024-03-28

最初的问题是我想在模板非类型参数中使用const char*char []。当然,现在不支持它。所以我想写一些代码来将char[]转换为std::integer_sequence。但我发现了一个严重的问题。

#include<utility>
template<typename T, std::size_t n>
constexpr auto f3(T (&a)[n])
{
return std::integer_sequence<T,a[0]>(); //simplified, it should be <T, a[i],...>
}
template<typename T, std::size_t n>
constexpr auto f2(T (&a)[n])
{
constexpr T v=a[3];
//.....other code
return v;
}
template<typename T, std::size_t n>
constexpr auto f1(T (&a)[n])
{
return a[3];
}
int main() 
{
constexpr char a[]="abcdefg";
constexpr auto v1=f1(a);
//constexpr auto v2=f2(a);
//constexpr auto v3=f3(a);
}

https://godbolt.org/z/E5YPTM

f1是可以的,但是f2&f3是错误的。我搞糊涂了。。。。。为什么?看起来只有";return xxx[yyy]"在编译时是可以的。我不能将它存储在值中,也不能将它传递给其他函数。

constexpr函数可能在非constexpr上下文中调用,因此参数永远不是constexpr:

a不是constexpr,因此f2/f3不能在constexpr上下文中使用它。

f1很好,a[3]不用于constexpr上下文。并且CCD_ 14可以用在具有适当自变量的常数表达式中。