vendredi 1 septembre 2017

Compile-time types generation in constexpr functions

#include <array>
#include <tuple>

typedef std::tuple<const int> TupleType;

constexpr std::array<const int, 2> a = {1, 2};

constexpr void foo()
{
    for (std::size_t i = 0; i < a.size(); ++i)
    {
        const int j = i;
        typedef std::tuple_element<j, TupleType> T;
    }
}

The code can not be compiled by gcc-7.2 with --std=c++17 with the following compilation error:

error: the value of 'j' is not usable in a constant expression
note: in template argument for type 'long unsigned int'

If we assume that function (and the corresponding loop) is evaluated in compile-time (which is viable for loops starting from c++14), why then this code can not be compiled as far as, even though i is not declared as const, it can actually be constexpr as all of its values are known at compile-time as well.

Could you please clarify whether this code is invalid by its very idea? Or there is a compiler limitation? Or none of the following?

Aucun commentaire:

Enregistrer un commentaire