問題描述
我有一個帶有 varargs 模板參數的模板函數,就像這樣
I have a template function with varargs template arguments, like this
template<typename Args...>
void ascendingPrint(Args... args) { /* ... */ }
我想寫
template<typename Args...>
void descendingPrint(Args... args) {
/* implementation using ascendingPrint()? */
}
我如何反轉參數包 args
的順序,然后再傳遞它,即在偽代碼中:
How do I reverse the order of the parameter-pack args
before passing it along, i.e. in pseudo-code:
template<typename Args...>
void descendingPrint(Args... args) {
ascendingPrint( reverse(args) );
}
推薦答案
這里是一個遞歸的特殊revert<>
實現:
Here is a recursive implementation of a specialized revert<>
:
// forward decl
template<class ...Tn>
struct revert;
// recursion anchor
template<>
struct revert<>
{
template<class ...Un>
static void apply(Un const&... un)
{
ascendingPrint(un...);
}
};
// recursion
template<class T, class ...Tn>
struct revert<T, Tn...>
{
template<class ...Un>
static void apply(T const& t, Tn const&... tn, Un const&... un)
{
// bubble 1st parameter backwards
revert<Tn...>::apply(tn..., t, un...);
}
};
// using recursive function
template<class A, class ...An>
void descendingPrint(A const& a, An const&... an)
{
revert<An...>::apply(an..., a);
}
它適用于 gcc-4.6/7/8 和 clang 并且可能符合標準——唯一困難的部分是調用revert
.
It works with gcc-4.6/7/8 and clang and is probably standard compliant -- the only difficult part being the call of revert<Tn...>::apply(tn..., t, un...)
.
雖然它有缺點(就像遞歸經常有的那樣),它會生成目標函數的大量模板實例(代碼膨脹)并且不使用完美轉發,這可能是一個問題(但也許可以改進使用它).
It has drawbacks though (as recursion often has), that it generates a lot of template-instantiations of the target function (code bloat) and does not use perfect forwarding, which may be an issue (but maybe could be improved to use it).
這篇關于如何反轉可變參數模板函數的參數順序?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!