简体   繁体   中英

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 (eg f(2, 2) is an error, but f(2, '2') is ok).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM