Search code examples
c++constexprconstexpr-function

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


The origin problem is I want to use const char* or char [] in template non-type arguments. Of course it is not supported now. So I want to write some code to convert char[] to std::integer_sequence. But I found a seriously problem.

#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

The f1 is ok but f2 & f3 are wrong. I confused..... Why is that? It looks like that only "return xxx[yyy]" is ok for compile-time. I can not store it in value or passing it to other functions.


Solution

  • constexpr functions might be called in non constexpr context, so parameters are never constexpr:

    a is not constexpr, so f2/f3 cannot use it in constexpr context.

    f1 is fine, a[3] is not used in constexpr context. and f1 can be used in constant expression with appropriate argument.