代码之家  ›  专栏  ›  技术社区  ›  Vincent

将可变模板类的模板参数解压缩为常量和常量数组

  •  4
  • Vincent  · 技术社区  · 13 年前

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

    做这样的事有什么“把戏”吗?

    非常感谢。

    2 回复  |  直到 13 年前
        1
  •  4
  •   Mr.Anubis    13 年前

    以下是实现其他两个功能的方法:

    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

        2
  •  1
  •   Aaron McDaid    13 年前

    这是一个部分答案,确实如此 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;
    }