Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force expression to constexpr

Given the two constexpr functions, is it possible to combine them into one function?

template <char... C>
constexpr int boo()
{
    char ch[] = { C... };
    int count = 0;

    for (char c : ch)
    {
        if (c != '0') count += 1;
    }

    return count;
}

template <char... C>
constexpr auto foo()
{
    std::array<char, boo<C...>()> x{};

    return x;
}

As the example shows I can return 'count' as a constant. My problem is I can't use 'count' as a constant in the function it's declared. That is if the body of 'boo()' is placed in 'foo()', the compiler throws up with 'count' not being a constant.

like image 876
Rlyeh Avatar asked Mar 21 '26 21:03

Rlyeh


1 Answers

The problem is that std::array needs a constant as size value.

If you define count and modify it inside foo(), count (as seen inside the foo() function) is a variable, not a constant.

So you need to modify it in another place: in a constexpr function, so the returned value become a compile-time known constant.

If you can use C++17, so template folding (with improvement from Evg and Rakete1111; thanks), you can avoid bar() at all

template <char... C>
constexpr auto foo()
{
    std::array<char, (0u + ... + (C != '0'))> x{};

    return x;
}

but if you have only C++11, you need recursion

template <typename = void>
constexpr std::size_t bar ()
 { return 0u; }

template <char C0, char ... C>
constexpr std::size_t bar ()
 { return bar<C...>() + (C0 == '0' ? 0u : 1u); }

template <char... C>
constexpr std::array<char, bar<C...>()> foo()
 { return {}; }
like image 71
max66 Avatar answered Mar 24 '26 09:03

max66



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!