简体   繁体   中英

C++ Constexpr Function

could anyone help me to understand why this code snippet won't compile?

#include <iostream>
#include <tuple>
#include <string_view>

constexpr auto Fields()
{
    using namespace std::string_view_literals;

    return std::tuple(
        std::tuple("campo_1"sv, 123),
        std::tuple("campo_2"sv, 456),
        std::tuple("campo_3"sv, 890),
        std::tuple("campo_4"sv, 136));
}

template<typename Tuple>
constexpr auto ProcessTupleElement(Tuple &&tuple)
{
    //constexpr auto ccb = std::get<1>(tuple); // 1 uncomment to get an error
    //char sx[ccb]; // 1 uncomment to get an error
    //(void)sx;
    return std::get<1>(tuple);
}

template<typename Tuple>
constexpr auto IterateTupleImpl(Tuple &&t)
{
    return ProcessTupleElement(std::get<0>(std::forward<Tuple>(t)));
}

template<typename Tuple>
constexpr auto IterateTuple(Tuple &&t)
{
    return IterateTupleImpl(std::forward<Tuple>(t));
}

int main()
{
    constexpr auto aa = IterateTuple(Fields()); // 2
    char sx[aa];
    (void)sx;
    return 0;
}

The code is just for testing purposes, I'm trying to figure out why in main function (comment "2") I'm able to define a constexpr variable which I then use to define a C-array size, but trying to do the same in function ProcessTupleElement (marked whit comment "1") I'm receiving a compiler error saying that:
prog.cc:19:20: error: '* & tuple' is not a constant expression
19 | constexpr auto ccb = std::get<1>(tuple);
prog.cc:20:10: error: size of array is not an integral constant-expression
20 | char sx[ccb]; // 1

As extra information, I'm compiling with GCC (C++ 17). My idea behind this test is to iterate in compile time a tuple like the one defined inside Fields function to test whether it has repeated names, but I can't manage to solve a previous problem, IE constexpr ness of function + variables.

argument are not constexpr (even when use with constexpr at call site).

Remember that constexpr function might be called as regular function.

Btw, you might have simplified your example to

constexpr int identity(int n)
{
    // constexpr int i = n; // Invalid
    return n;
}

constexpr int the_answer = identity(42);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM