问题描述
我有一个这样声明的ctor:
I have a ctor declared like this:
template<typename... Coords>
MyClass<T>(vector<T> values, Coords... coords) { /* code */ }
我希望它看起来像这样:
I want it to look like this:
template<typename... Coords>
MyClass<T>(Coords... coords, vector<T> values) { /* code */ }
,但标准要求可变参数为最后一个参数.如果我写类似
but the standard requires the variadic argument to be the last. If I write something like
template<typename... Args>
MyClass<T>(Args... coordsThenValues) { /* code */ }
我如何将 coordsThenValues
拆分为最后一个参数包 Coords ... coords
和最后一个参数 vector< T>值
?
how would I split coordsThenValues
into an all-but-last parameter pack Coords... coords
and the last parameter vector<T> values
?
推荐答案
您喜欢元组吗?
你喜欢像元组一样转发吗?
How do you like forward as tuple?
struct foo {
template<class...Ts>
foo(Ts&&...ts):
foo(
magic<0>{}, // sent it to the right ctor
std::index_sequence< sizeof...(ts)-1 >{}, // the last shall be first
std::make_index_sequence<sizeof...(ts)-1>{}, // the first shall be last
std::forward_as_tuple(std::forward<Ts>(ts)...) // bundled args
)
{}
private:
template<size_t>
struct magic {};
template<size_t...I0s, size_t...I1s, class...Ts>
foo(
magic<0>, // tag
std::index_sequence<I0s...>, // first args
std::index_sequence<I1s...>, // last args
std::tuple<Ts&&...> args // all args
):
foo(
magic<1>{}, // dispatch to another tagged ctor
std::get<I0s>(std::move(args))..., // get first args
std::get<I1s>(std::move(args))... // and last args
)
{}
// this ctor gets the args in an easier to understand order:
template<class...Coords>
foo(magic<1>, std::vector<T> values, Coords...coords) {
}
};
在这里,公共ctor将参数打包成一个引用元组(可能是l,可能是r).它还获得了两组索引.
here the public ctor packs up the arguments into a tuple of references (possibly l, possibly r). It also gets two sets of indexes.
然后将其发送到 magic< 0>
ctor,后者将参数变乱,以便最后一个在前(假设索引正确).
It then sends it to magic<0>
ctor, which shuffles the arguments around so that the last one is first (assuming the indexes are right).
magic< 1>
ctor首先获取矢量,然后获取坐标.
The magic<1>
ctor gets the vector first, then the coords.
基本上,我将参数打乱了,所以最后一个变成了第一个.
Basically I shuffled the arguments around so the last one became first.
魔术
的存在是为了让我不必过多考虑过载解析,并且使我要转发给哪个ctor明确.如果没有它,它可能会起作用,但是当我对ctor转发进行疯狂的操作时,我喜欢添加标签.
magic
just exists to make me not have to think much about overload resolution, and make which ctor I'm forwarding to explicit. It would probably work without it, but I like tagging when I'm doing something crazy with ctor forwarding.
这篇关于获取可变参数模板的所有最后参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!