Search code examples
c++c++17stdapply

std::apply and constant expression?


I tried code below in Wandbox:

#include <array>
#include <iostream>
#include <tuple>
#include <typeinfo>
#include <functional>
#include <utility>


int main()
{
    constexpr std::array<const char, 10> str{"123456789"};
    constexpr auto foo = std::apply([](auto... args) constexpr { std::integer_sequence<char, args...>{}; } , str);
    std::cout << typeid(foo).name();
}

and the compiler told me that args... are not constant expression. What's wrong?


Solution

  • All constexpr functions must be valid both constexpr and not, even if marked constexpr.

    There is a proposal for a constexpr literal that passed characters as non type template parameters. Then "hello"_bob could expand directly to a parameter pack.

    Another approach is you can pass std::integral_constant<T, t> to the lambda through some mechanism, like my indexer. Then converting to T is constexpr even tho the variable is not. This does not help you with "hello" to a sequence.