Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Hacky parameter pattern with variadic arguments

Is it possible to use C++ variadic arguments to define a function that allows exactly the following calls:

f(int, char)
f(int, char, char)
f(int, char, char, int)
f(int, char, char, int, char)
...

Where every nth argument is a char if n is a prime number, and otherwise it is an int. The function can only be called in this way; it does not compile with other parameter patterns (e.g. f(2, 2) is an error, but f(2, '2') is ok).

like image 476
Kevin Meier Avatar asked Dec 24 '22 05:12

Kevin Meier


1 Answers

Assuming:

constexpr bool is_prime(size_t);

Then something like this:

template <typename... Ts> struct typelist;

template <size_t... Is>
constexpr auto expected(std::index_sequence<Is...>)
    -> typelist<std::conditional_t<is_prime(Is+1), char, int>...>;

template <typename... Ts,
    std::enable_if_t<std::is_same<
        typelist<Ts...>,
        decltype(expected(std::index_sequence_for<Ts...>{}))
        >::value, int> = 0>
auto f(Ts... ts);
like image 126
Barry Avatar answered Dec 28 '22 07:12

Barry