Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic template parameters of one specific type

Why there is no specific type allowed in a variadic template pack?

template< typename T >
class Foo
{
public:
    template< typename... Values >
    void bar( Values... values )
    {
    }

    template< T... values >            <-- syntax error
    void bar( T... values )
    {
    }

    template< int... values >          <-- syntax error
    void bar( int... values )
    {
    }
};

Whats the rationale in not allowing this?
Are there proposals for this?


Note: alternatives would be

  • std::initializer_list< T > without narrowing of types and the { }-brace-syntax
  • a (ugly) recursive trait that checks all types seperately: see here
like image 400
nonsensation Avatar asked Jun 11 '15 06:06

nonsensation


People also ask

What is special about Variadic functions?

Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.

Which of the following are valid reasons for using variadic templates in C++?

Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue.

What is Variadic template in C++?

A variadic template is a class or function template that supports an arbitrary number of arguments. This mechanism is especially useful to C++ library developers: You can apply it to both class templates and function templates, and thereby provide a wide range of type-safe and non-trivial functionality and flexibility.

What is parameter pack in c++?

Parameter packs (C++11) A parameter pack can be a type of parameter for templates. Unlike previous parameters, which can only bind to a single argument, a parameter pack can pack multiple parameters into a single parameter by placing an ellipsis to the left of the parameter name.


1 Answers

It IS allowed, actually, you're just using it wrong. T... and int... are non-type parameter packs and their elements are values, so you can't use them as type specifiers (and you can't deduce them from a function call).

An example of correct usage:

template<int... Is>
struct IntPack {};

IntPack<1,2,3> p;

or

template< typename T >
struct Foo
{
    template< T... Ts>
    void bar()
    {
    }
};

int main()
{
    Foo<int> f;
    f.bar<1,2,3>();
}

Another example would be std::integer_sequence.

like image 144
jrok Avatar answered Nov 03 '22 08:11

jrok