4

我对 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}

};

做这样的事情有什么“技巧”吗?

非常感谢你。

4

2 回答 2

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

于 2012-08-04T17:44:47.753 回答
1

这是部分答案,它确实order_constsize_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;
}
于 2012-08-04T00:39:20.907 回答