我对C ++ 2011的可变参数模板很陌生,我想知道是否存在执行以下操作的技巧:
template<typename T, unsigned int... TDIM> class VariadicTest
{
public:
static const unsigned int order_const = sizeof...(TDIM);
static const unsigned int size_const = // TDIM1*TDIM2*TDIM3...
static const unsigned int dim_const[order_const] = // {TDIM1, TDIM2, TDIM3...}
// if not possible :
// dim_const[64] = {TDIM1, TDIM2, TDIM3, 0, ..., 0}
};
有没有“技巧”来做这样的事情?
非常感谢。
答案 0 :(得分:4)
以下是实现其他两项功能的方法:
template<unsigned int... T> struct mul;
template<unsigned int L,unsigned int... T> struct mul<L,T...>
{
static const int val= L*mul<T...>::val;
};
template<unsigned int L> struct mul<L>
{
static const int val= L;
};
template<typename T, unsigned int... TDIM> class VariadicTest
{
public:
static const unsigned int order_const = sizeof...(TDIM);
static const unsigned int size_const = mul<TDIM...>::val;
static const unsigned int dim_const[order_const];
};
template<typename T, unsigned int... TDIM>
const unsigned int VariadicTest<T,TDIM...>::dim_const[order_const] = {TDIM...};
测试:http://liveworkspace.org/code/cfb0ec09a05931cfcc00edf29866e716
答案 1 :(得分:1)
以下是部分答案,order_const
和size_const
。但我还看不到如何做dim_const
。
#include<iostream>
using namespace std;
template<typename T, unsigned int... TDIM>
class VariadicTest;
template<typename T>
class VariadicTest<T>
{
public:
static const unsigned int order_const = sizeof...(TDIM);
static const unsigned int size_const = 1;
};
template<typename T, unsigned int baseTDIM, unsigned int... others>
class VariadicTest<T, baseTDIM, others...>
{
public:
static const unsigned int order_const = sizeof...(TDIM);
static const unsigned int size_const = baseTDIM * VariadicTest<T,others...> :: size_const;
};
int main() {
VariadicTest<double, 9, 4, 5> x;
cout << x.order_const << endl;
cout << x.size_const << endl;
}