C++:具有可变参数的Hacky参数模式

Kev*_*ier 4 c++ variadic-functions c++11 c++14

是否可以使用C++可变参数来定义一个允许以下调用的函数:

f(int, char)
f(int, char, char)
f(int, char, char, int)
f(int, char, char, int, char)
...
Run Code Online (Sandbox Code Playgroud)

其中每个第n个参数是a,char如果n是素数,否则它是a int.该功能只能以这种方式调用; 它不能与其他参数模式一起编译(例如f(2, 2)是一个错误,但f(2, '2')没关系).

Bar*_*rry 10

假设:

constexpr bool is_prime(size_t);
Run Code Online (Sandbox Code Playgroud)

然后这样的事情:

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);
Run Code Online (Sandbox Code Playgroud)