问题描述
如何将可变参数模板参数分成两半?例如:
How do I split variadic template arguments in two halves? Something like:
template <int d> struct a {
std::array <int, d> p, q;
template <typename ... T> a (T ... t) : p ({half of t...}), q ({other half of t...}) {}
};
推荐答案
我们仍然缺乏很多帮助来操纵可变参数包(或我不知道他们)。
We still lack a lot of helpers to manipulate variadic parameter packs (or I am not aware of them). Until a nice Boost library bring them to us, we can still write our own.
例如,如果你愿意将你的数组初始化推迟到构造函数体中,那么,可以创建和使用将部分参数包复制到输出迭代器的命令:
For example, if you are willing to postpone your arrays initialization to the constructor body, you can create and use a fonction that copies part of the parameter pack to an output iterator:
#include <array>
#include <cassert>
#include <iostream>
// Copy n values from the parameter pack to an output iterator
template < typename OutputIterator >
void copy_n( size_t n, OutputIterator )
{
assert ( n == 0 );
}
template < typename OutputIterator, typename T, typename... Args >
void copy_n( size_t n, OutputIterator out, const T & value, Args... args )
{
if ( n > 0 )
{
*out = value;
copy_n( n - 1, ++out, args... );
}
}
// Copy n values from the parameter pack to an output iterator, starting at
// the "beginth" element
template < typename OutputIterator >
void copy_range( size_t begin, size_t size, OutputIterator out )
{
assert( size == 0 );
}
template < typename OutputIterator, typename T, typename... Args >
void copy_range( size_t begin, size_t size, OutputIterator out, T value, Args... args )
{
if ( begin == 0 )
{
copy_n( size, out, value, args... );
}
else
{
copy_range( begin - 1, size, out, args... );
}
}
template < int N >
struct DoubleArray
{
std::array< int, N > p;
std::array< int, N > q;
template < typename... Args >
DoubleArray ( Args... args )
{
copy_range( 0, N, p.begin(), args... );
copy_range( N, N, q.begin(), args... );
}
};
int main()
{
DoubleArray<3> mya(1, 2, 3, 4, 5, 6);
std::cout << mya.p[0] << mya.p[2] << std::endl;
std::cout << mya.q[0] << mya.q[2] << std::endl;
}
// Ouput:
// 13
// 46
正如你所看到的,你可以(不是这样)轻松地创建自己的算法来操纵参数包;所有需要的是一个很好的递归和模式匹配的理解(像做模板MetaProgramming时一样...)。
As you can see, you can (not so) easily create your own algorithms to manipulate parameter packs; all is needed is a good understanding of recursion and pattern matching (as always when doing Template MetaProgramming...).
这篇关于拆分可变参数模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!