Home > Enterprise >  Receive variadic sized raw arrays of the same type in a C template function
Receive variadic sized raw arrays of the same type in a C template function

Time:10-06

I would like to implement the following logic, I'm not sure if it is possible:

#include <stddef.h>
#include <array>

template<size_t SIZE>
constexpr std::array<const char*, 1> fun(const char (&name)[SIZE])
{
    return {name};
}

template<size_t SIZE_1, size_t SIZE_2>
constexpr std::array<const char*, 2> fun(const char (&name1)[SIZE_1], const char (&name2)[SIZE_2])
{
    return {name1, name2};
}

// I would like to do something like this:
template<size_t... SIZES>
constexpr std::array<const char*, sizeof...(SIZES)> fun(const char (&/*???*/)[SIZES]/*...*/)
{
    //???
}

int main()
{
    static constexpr auto fun1 = fun("aaa");
    static constexpr auto fun2 = fun("aaa", "bbb");
    //static constexpr auto funN = fun("aaa", "bbb", "ccc");
}

It is important to get the parameters as raw arrays to do additional compile time magic on them.

CodePudding user response:

Knowing where to put the ... is much simpler with a type alias

template<std::size_t N>
using chars = const char (&)[N];

template<std::size_t... SIZES>
constexpr std::array<const char*, sizeof...(SIZES)> fun(chars<SIZES>... names)
{
    return { names... };
}

See it on coliru

  • Related