The number of function arguments is an integer number of patterns

Say I have a class with an integer template argument. How can I add a function that takes arguments of a Ngiven type? If at all possible, I would like to avoid the enable_iflike.

What am I doing now:

template<unsigned int N>
class Foo
{
    template <typename To, typename>
    using to = To;
public:
    template<typename... Args>
    void Bar(to<char, Args>... args) // Some arguments of type char
    { /* do stuff */ }
};

This allows you to call Bar:

Foo<3> myfoo;
myfoo.Bar<int, int, int>('a', 'b', 'c');

However, I see two flaws. First, the number of arguments is not necessarily limited N, with the possible exception of the code inside Bar.

Secondly, the user needs to add template parameters to the function. Their values โ€‹โ€‹are not actually used, but only the number of arguments. This seems unnecessary as we already have it, namely N.

Optimal use of the function would look like this:

Foo<3> myfoo;
myfoo.Bar('a', 'b', 'c'); // valid

. function does not take this many arguments , , void(char, char, char) .

myfoo.Bar('a', 'b');
myfoo.Bar('a', 'b', 'c', 'd'); // error
myfoo.Bar('a', 'b', "flob"); // error
// ...
+1
1

++ 14, :

#include <utility>

template<std::size_t N, class = std::make_index_sequence<N>>
class Foo;

template<std::size_t N, std::size_t... Is>
class Foo<N, std::index_sequence<Is...>>{
    void Bar(decltype(Is, char{})... args) // Some arguments of type char
    { /* do stuff */ }
};

[live demo]

++ 11 integer_sequence, ... , this

+3

Source: https://habr.com/ru/post/1661891/


All Articles