简体   繁体   English

具有相等参数类型的可变参数模板函数

[英]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. 显然,C ++不允许这样做,因为需要在...args的左侧有一个模板参数包才能使用。 What I want is a template function where all argument types are the same. 我想要的是一个模板函数,其中所有参数类型都相同。 Is there an easy way to do that? 有一个简单的方法吗?

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

or from std::experimental 或者来自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. void使返回类型成为输入参数的common_type ,否则,如果您知道,则可以明确指定您想要的类型。

#include <tuple>
#include <type_traits>

template <typename T, typename... Ts>
auto f(const T& t, const Ts&... ts)
    -> typename std::enable_if<std::is_same<std::tuple<T, Ts...>
                                          , std::tuple<Ts..., T>
                              >::value>::type
{
}

DEMO DEMO

I'd add one more solution to the ones already proposed. 我将为已经提出的解决方案添加一个解决方案。
You can also use an initializer_list to do that. 您也可以使用initializer_list来执行此操作。
It follows a working example: 它遵循一个工作示例:

#include<initializer_list>
#include<vector>
#include<string>

template<class T>
void fn(std::initializer_list<T> l) {
    std::vector<T> v(l);
    // so on
}

int main() {
    fn<std::string>({ "foo", " bar" });
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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