【问题标题】:c++ how to use constexpr value with operator []c ++如何将constexpr值与运算符[]一起使用
【发布时间】:2021-06-16 19:32:44
【问题描述】:

起源问题是我想在模板非类型参数中使用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]”对于编译时是可以的。我无法将其存储在值中或将其传递给其他函数。

【问题讨论】:

标签: c++ constexpr constexpr-function


【解决方案1】:

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

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

f1 很好,a[3] 不在constexpr 上下文中使用。 并且f1 可以在带有适当参数的常量表达式中使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2011-07-29
    • 2019-01-17
    相关资源
    最近更新 更多