做一两件事的时间:
template<class R>
R sort_the_range(R&& r) {
using std::begin; using std::end;
std::sort(begin(r), end(r));
return std::forward<R>(r);
}
一些元编程:(花样式)
template<class T> struct tag{using type=T;};
template<class...> struct types{using type=types;};
template<class Tag>using type_t=typename Tag::type;
template<class Default, class...Ts,
class=typename std::enable_if<!std::is_same<void,Default>::value>::type
>
constexpr tag<Default> type_from(tag<Default>, Ts...) { return {}; }
template<class T0, class...Ts>
constexpr tag<T0> type_from(tag<void>, tag<T0>, Ts...) { return {}; }
template<class Default, class...Ts>
using type_from_t = type_t< decltype(type_from(tag<Default>{}, tag<Ts>{}...)) >;
现在,一个函数,使一个向量。你可以在一个类型传递的载体,或者它的第一个参数推断,你的选择:
// explicit T argument is optional:
template<class ExplicitType=void, class...Ts,
// deduce return type:
class R=type_from_t<ExplicitType, typename std::decay<Ts>::type...>
>
std::vector<R> make_vector(Ts&&... ts) {
// block explicit conversions:
using test = decltype(std::array<R, sizeof...(Ts)>{{ std::declval<Ts>()... }});
(void)tag<test>{}; // block warnings
// make our vector, and size it right:
std::vector<R> retval;
retval.reserve(sizeof...(ts));
// populate the vector:
(void)std::initializer_list<int>{0,((
retval.emplace_back(std::forward<Ts>(ts))
),void(),0)...};
return retval;
}
和缝合:
template<class T=void, class...Ts>
auto make_sorted_vector(Ts&&...ts)
->decltype(make_vector<T>(std::forward<Ts>(ts)...))
{
return sort_the_range(
make_vector<T>(std::forward<Ts>(ts)...)
);
}
live example)
有什么理由不在这里使用initializer_list,比如说,有一个像sort({varA,varB,varC,varD})这样的排序例程? – templatetypedef
你实际上并没有对模板参数进行排序('T,Args ...'),对吧?你想实际排序'首先,休息...'? @templatetypedef这将强制一个副本。这一个不必如果与转发参考正确地撒上。 –