【问题标题】:Is there anything similar to constexpr for C++03 in this context?在这种情况下,C++03 是否有类似 constexpr 的东西?
【发布时间】:2014-06-10 13:03:43
【问题描述】:

假设我有一个带有整数模板参数的模板类A,以及一个派生自A 特化的类B(可能有许多具有不同特化A 的此类派生类)。我想能够问B它的基类有什么模板参数,并从基类中调用相应的静态函数。

使用 C++11 constexpr 关键字很容易做到这一点,但 C++03 中不存在这样的关键字。因此,此代码无法在 C++03-(假定)兼容行上使用 C++11 编译器编译:

template<int N>
struct A
{
    static const int getN() { return N; }
    static constexpr int getNc() { return N; }

    static int g(const A& a) { return 123; }
};

struct B : public A<4>
{   
};

int main()
{
    A<B::getNc()>::g(B()); // OK in C++11
    A<B::getN()>::g(B()); // FAIL in any C++ version
}

那么,问题是,我如何在 C++03 中实现相同的功能?也许有一些语法糖可以避免在main() 中明确指定A 的模板参数?

【问题讨论】:

    标签: c++ templates constants


    【解决方案1】:

    在 C++03 中,常量表达式可以是静态常量变量

    static const int value = N;
    

    或枚举器

    enum {value = N};
    

    您可以访问其中任何一个

    A<B::value>::g(B());
    

    也许有一些语法糖可以避免显式指定 A 的模板参数

    你可以提供一个非会员辅助函数:

    template <class DerivedFromA>
    int g(const DerivedFromA & a) {
        return A<DerivedFromA::value>::g(a);
    }
    
    // usage
    g(B()); // equivalent to A<B::value>::g(B());
    

    【讨论】:

      【解决方案2】:

      使用static const 数据成员代替函数:在A 中放入

      static const int NVal = N;
      

      然后B::NVal 会给你N 模板参数的值作为编译时常量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-08
        相关资源
        最近更新 更多