4
votes

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).

1
Please show us what you have tried. It might also not be a bad idea to explain a possible use-case. - Henri Menke
you know that a f(int,char) can be called as f(2,2) without error and are seeking for a way to make it an error or is it sufficient to get the signature right? - 463035818_is_not_a_number
Actually, there is no use-case for this. I just wanted to know if it is possible;-) Thanks for the hint with the auto-casting; I do not care about the used types in the signature, but more about how to create this pattern. - Kevin Meier

1 Answers

10
votes

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);