是否有等价的#if可以评估模板参数?

时间:2016-06-13 11:04:38

标签: c++ templates macros

#if预处理器指令计算"常量"的表达式。预处理器已知。是否有类似的东西可以评估模板参数的表达式?

在实践中,我有类似的东西:

template<int i>    
class Elem{ /*...*/};

#ifndef NUM_ELEM
#define NUM_ELEM 2 
#endif    

class MyClass
{

    #if NUM_ELEM >= 1
        Elem<1> e_1;
    #endif
    #if NUM_ELEM >= 2
        Elem<2> e_2;
    #endif
    #if NUM_ELEM >= 3
        Elem<3> e_3;
    #endif

    /*...*/
}

但我真的很想将MyClass变成模板:

template<int num_elem>
MyClass{

    #if num_elem >= 1 //but #if can't understand num_elem
        Elem<1> e_1;
    #endif
    #if num_elem >= 2
        Elem<2> e_2;
    #endif
    #if num_elem >= 3
        Elem<3> e_3;
    #endif 

    /*...*/
};

1 个答案:

答案 0 :(得分:7)

简短的回答是否定的,但如果您愿意稍微改变一下您的要求,可以采取以下措施:

// A run of elements - Elem<n>, ..., Elem<2>, Elem<1>
template <int n> class NumElems
{
    template <int u, int v> friend class ElemGetter;

    NumElems<n-1> before;

    public:
    Elem<n> e;

    // method to retrieve an element by number
    template <int m> Elem<m> &getElem();
};

// helper class to retrieve an element.
//  'n' is the element number to retrieve
//  'm' is the number of elements
// by default, ElemGetter<n,m> defers to ElemGetter<n,m-1>.
template <int n, int m> class ElemGetter
{
    public:
    static Elem<n> &getElem(NumElems<m> &numElems)
    {
        return ElemGetter<n,m-1>::getElem(numElems.before);
    }
};

// specialisation of ElemGetter: if the element to get is the same as the
// number of elements (i.e. is the last element) then return it
// immediately.
template <int n> class ElemGetter<n,n>
{
    public:
    static Elem<n> &getElem(NumElems<n> &numElems)
    {
        return numElems.e;
    }
};

// get an element by number; defers to the ElemGetter helper.
template <int n> template <int m> Elem<m> &NumElems<n>::getElem()
{
    return ElemGetter<m,n>::getElem(*this);
}

template <> class NumElems<0>
{
};

...然后你可以用:

声明你的Elem成员集
NumElems<NUM_ELEM> elems;

您可以使用以下方式访问它们:

Elem<2> &e = elems.getElem<2>();

原始建议代码

我提议的原始代码实际上并没有编译,但是我会在这里包含它,因为它更好地演示了上面的 intent

// Original, doesn't compile - but it would be nice if it did :/
template <int n> class NumElems : private NumElems<n-1>
{
    Elem<n> e;

    template <int m> Elem<m> &getElem()
    {
        return NumElems<n-1>::getElem<m>();
    }

    template <> Elem<n> &getElem<n>()
    {
        return e;
    }
};

template <> class NumElems<0>
{
};

不幸的是,C ++不允许以这种方式对成员模板函数进行专门化,虽然它不清楚(对我而言)为什么不 - 代码肯定更简单,而不必创建一个帮助类,就像在工作中一样上面的代码。