【发布时间】:2016-08-27 22:38:36
【问题描述】:
而不是像这样创建向量:
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,这是我对向量的尝试:
#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);
我怎样才能制定一个通用的例程,
使用第一个参数的第一个类型来实例化向量?
如何将参数作为初始值设定项转发给向量?
【问题讨论】:
标签: c++ templates c++11 variadic-templates perfect-forwarding