std_unordered_map
std_unordered_map

Reputation: 113

Getting the value of a constexpr std::variant via constexpr function

This is a reduced example of a bigger function. The core issue is that at one point I try to get the value out of a constexpr std::variant via a constexpr/consteval function. This fails and I do not know why.

Code:

#include <type_traits>
#include <variant>

constexpr auto f2(const auto& a_variant)
{
    if (std::is_constant_evaluated())
        return std::get<a_variant.index()>(a_variant);
    else
        return 0;
}

consteval auto f3(const auto& a_variant)
{
    return std::get<a_variant.index()>(a_variant);
}

void f()
{
    constexpr auto v = std::variant<int, double>{1};

    // works
    [[maybe_unused]] constexpr auto r = std::get<v.index()>(v);

    // fails
    constexpr auto r2 = f2(v);
    constexpr auto r3 = f3(v);
}

Result:

... error: 'a_variant' is not a constant expression 7 | return std::get<a_variant.index()>(a_variant); ...

https://godbolt.org/z/4156oo5Gf

Upvotes: 1

Views: 44

Answers (0)

Related Questions