而不是像这样创建 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_pair和 std::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/