Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic template function with equal argument types

I would like to write a template function like so:

template <typename T>
void f( const T & ...args ) // <-- This doesn't work, unfortunately.
{
    std::array<T> arr = { args... };
    // and so forth.
}

Apparently, C++ does not allow that, because there needs to be a template parameter pack on the left-hand side of ...args for this to work. What I want is a template function where all argument types are the same. Is there an easy way to do that?

like image 979
Ralph Tandetzky Avatar asked Dec 14 '15 17:12

Ralph Tandetzky


1 Answers

    template <typename ... T>
    void f(const T & ... args)
    {
        std::array<typename std::common_type<T...>::type,
                   sizeof...(T)> arr = {args...};
    }

or from std::experimental

   template <typename ... T>
   void f(const T & ... args)
   {
        auto arr = std::experimental::make_array<void>(args...);
   }

The void makes the return type be the common_type of the input parameters, else you can specify what type you want explicitly if you know it.

like image 92
SirGuy Avatar answered Nov 15 '22 20:11

SirGuy