这make_vector
是一个函数,它接受任意数量的参数,并将它们完美地转发到一个向量中。
// get the first type in a pack, if it exists:
template<class...Ts>
struct first {};
template<class T, class...Ts>
struct first<T,Ts...>{
using type=T;
};
template<class...Ts>
using first_t=typename first<Ts...>::type;
// build the return type:
template<class T0, class...Ts>
using vector_T =
typename std::conditional<
std::is_same<T0, void>::value,
typename std::decay<first_t<Ts...>>::type,
T0
>::type;
template<class T0, class...Ts>
using vector_t = std::vector< vector_T<T0, Ts...> >;
// make a vector, non-empty arg case:
template<class T0=void, class...Ts, class R=vector_t<T0, Ts...>>
R make_vector( Ts&&...ts ) {
R retval;
retval.reserve(sizeof...(Ts)); // we know how many elements
// array unpacking trick:
using discard = int[];
(void)discard{0,((
retval.emplace_back( std::forward<Ts>(ts) )
),void(),0)...};
return retval; // NRVO!
}
// the empty overload:
template<class T>
std::vector<T> make_vector() {
return {};
}
采用:
std::vector<std::unique_ptr<test1>> vec =
make_vector(
std::move(u1), std::move(u2)
);
活生生的例子
我稍微打磨了一下。如果您传递 1 个或多个 args 并且不传递类型,它将推断返回类型。如果你传递一个类型,它将使用该类型。如果你没有给它传递一个类型或任何参数,它会抱怨。(如果你转发包,或者以特定类型存储它,我总是给它一个类型)。
可以进行进一步的步骤,我们进行返回类型推导以消除即使在空情况下也需要指定类型的要求。这可能在您的用例中是必需的,我不知道,但它与您不需要指定 a 类型的方式相匹配{}
,所以我想我会把它扔在那里:
template<class...Ts>
struct make_vec_later {
std::tuple<Ts...> args; // could make this `Ts&&...`, but that is scary
// make this && in C++14
template<class T, size_t...Is>
std::vector<T> get(std::index_sequence<Is...>) {
return make_vector<T>(std::get<Is>(std::move(args))...);
}
// make this && in C++14
template<class T>
operator std::vector<T>(){
return std::move(*this).template get<T>( std::index_sequence_for<Ts...>{} );
}
};
template<class...Ts>
make_vec_later<Ts...> v(Ts&&...ts) {
return {std::tuple<Ts...>(std::forward<Ts>(ts)...)};
}
这确实依赖于 的 C++14 特性index_sequence
,但如果您的编译器还没有,这些特性很容易在 C++11 中重写。只需在堆栈溢出上搜索它,就有无数种实现。
现在语法看起来像:
std::vector<std::unique_ptr<test1>> vec =
v(std::move(u1));
其中参数列表可以为空。
活生生的例子
支持变体分配器留给用户作为练习。将另一种类型添加到make_vector
被调用A
,并使其默认为void
. 如果它是无效的,则将其交换为为向量选择的std::allocator<T>
任何类型。T
在返回类型推导版本中,做类似的事情。