c++ - 如何编写类似于 std::make_tuple 的 make_vector?

标签 c++ templates c++11 variadic-templates perfect-forwarding

而不是像这样创建 vector :

  std::vector<int>     v1{1,2,3};
  std::vector<double>  v2{1.1,2.2,3.3};
  std::vector<Object>  v3{Object{},Object{},Object{}};  

我想用通用函数创建它们:

  auto v1 = make_vector(1,2,3);
  auto v2 = make_vector(1.1,2.2,3.3);
  auto v3 = make_vector(Object{},Object{},Object{}); 

类似于std::make_pairstd::make_tuple ,这是我对 vector 的尝试:

#include <iostream>
#include <vector>
#include <utility>

template <typename... T>
auto make_vector(T&&... args)
{
    using first_type = typename std::tuple_element<0, std::tuple<T...>>::type;
    return std::vector<first_type>{std::forward<T>(args)...};
}

它可以编译,但是当我尝试使用它时:

auto vec = make_vector(1,2,3);  

m.cpp: In instantiation of ‘auto make_vector(T&& ...) [with T = {int, int, int}]’:
m.cpp:16:30:   required from here
m.cpp:8:78: error: invalid use of incomplete type ‘class std::tuple_element<0ul, std::tuple<int, int, int> >’
     using first_type = typename std::tuple_element<0, std::tuple<T...>>::type;
                                                                              ^
In file included from m.cpp:3:0:
/usr/include/c++/5/utility:85:11: note: declaration of ‘class std::tuple_element<0ul, std::tuple<int, int, int> >’
     class tuple_element;
           ^
m.cpp:9:60: error: invalid use of incomplete type ‘class std::tuple_element<0ul, std::tuple<int, int, int> >’
     return std::vector<first_type>{std::forward<T>(args)...};
                                                            ^
In file included from m.cpp:3:0:
/usr/include/c++/5/utility:85:11: note: declaration of ‘class std::tuple_element<0ul, std::tuple<int, int, int> >’
     class tuple_element;
           ^
m.cpp: In function ‘int main()’:
m.cpp:16:30: error: ‘void v1’ has incomplete type
   auto v1 = make_vector(1,2,3);  

我怎样才能制作一个通用例程,
那个使用第一个参数的第一个类型来实例化vector?
如何将参数作为初始化值转发给 vector ?

最佳答案

因为无论如何你都不能用它来创建一个空 vector ,我们可以通过提供一个额外的模板参数来避免 tuple 依赖:

template <class T0, class... Ts>
auto make_vector(T0&& first, Ts&&... args)
{
    using first_type = std::decay_t<T0>;
    return std::vector<first_type>{
        std::forward<T0>(first),
        std::forward<Ts>(args)...
    };
}

如果 first 作为左值传入,它还有一个额外的好处。

关于c++ - 如何编写类似于 std::make_tuple 的 make_vector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36994727/

相关文章:

c++ - 具有静态存储持续时间的对象中未初始化的指针是否初始化为 NULL 或全零?

c++ - 未初始化和不确定之间的区别

c++ - 如何使用模板化构造函数定义推导指南?

c++ - 使用 std::shared_ptr 时出现 malloc 错误

c++ - 为什么这段代码编译(C++11)没有类型不匹配错误?

java - 实现 DOM 意味着什么

c++ - __declspec(dllexport) 嵌套类

c++ - 在C++中创建大尺寸二维数组时出现段错误

c++ - 确定是否将相同的指针传递给宏

C++句柄/主体类自动由模板参数包组成。这可以改进吗?