【问题标题】:constant expression function in c++98c++98中的常量表达式函数
【发布时间】:2017-05-26 09:42:59
【问题描述】:

我在使用 c++98 常量表达式时遇到以下问题。 这是一个模板结构的示例..它将在编译时接收大小..

是否有可能在没有 c++11 constexpr 的情况下将此大小作为常量表达式? 看看GetCount()...

    template <typename ValueType, UInt32 size>
    struct FixedArray
    {
       ValueType mArr[size > 0 ? size : 1];
       UInt32 GetCount() const { return size; }

      ...
      other code
      ..
    }

我希望能够做这样的事情:

FixedArray<int , 10> a;
FixedArray<int , a.GetSize()> b;

编辑:

我找不到 C++ 98 的方法,似乎根本不可能。

【问题讨论】:

  • 您可以将数字映射到类型。见en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Int-To-Type
  • 人们现在正在加入 C++17。为什么要保持 19 年前的过时标准?
  • @DeiDei:大型软件堆栈是升级的障碍。但是,是的,现在真的应该至少迁移到 C++03。两年前我搬到了 C++11。我将安排在 2020 年的某个时候迁移到 C++17,并完全跳过 C++14。
  • @DeiDei 在我公司,我们必须支持现代和 c++98
  • @Bathsheba 也许吧,但我并不是真的买它。打开 C++14 编译器标志来重新编译旧项目可能不会破坏太多东西,如果有的话。至少不会在相当短的时间内修复太多。

标签: c++ templates c++98 compile-time-constant constant-expression


【解决方案1】:

似乎在 C++ 98 中没有办法做到这一点,它根本行不通。

【讨论】:

    【解决方案2】:

    您可以使用老式的 enum 元编程技巧:

    template <typename ValueType, UInt32 size>
    struct FixedArray
    {
        enum {value = size};
        // All your other stuff, but ditch your GetCount() function.
    };
    

    那么,

    FixedArray<int, 10> a;
    FixedArray<int, a.value> b;
    

    将在 C++98 下编译。

    【讨论】:

    • 还有办法保留GetCount函数吗?
    • 你可以拥有它return value;,但你不能在编译时使用它。 enum 方法几乎可以为您提供constexpr
    • UInt32 GetCount() const { return value; } 将。
    • 它仍然说“'UInt32'(又名'unsigned int')类型的非类型模板参数不是整数常量表达式”
    • 你什么时候使用这个功能?
    猜你喜欢
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多