微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

模板的内部枚举类不被视为常量表达式?

如何解决模板的内部枚举类不被视为常量表达式?

我将 C++ 与 GCC's C extension for designated inits / designated array initializers 一起使用,但我遇到了一些麻烦。如果我有以下(人为的)示例代码

#include <string>
#include <string_view>

struct STRUCTURE {
    enum class ENUM { A,B,C };
    static constexpr std::string_view STRINGS[] {
        [static_cast<int>(ENUM::A)] = "A",[static_cast<int>(ENUM::B)] = "B",[static_cast<int>(ENUM::C)] = "C"
    };

    constexpr std::string_view operator[](ENUM e) const {
        return STRINGS[static_cast<int>(e)];
    }
};

一切都按预期进行。但是,如果我现在对结构进行模板化,即

#include <string>
#include <string_view>

template <typename T>
struct STRUCTURE { /*same structure deFinition*/ };

我收到一个编译时错误,指出我拥有的 C99 指示符初始值设定项不是整数常量表达式。

事实上,在某些使用命名空间的情况下,我会收到内部编译器错误/内部编译器段错误,这让我相信这是一个内部问题,但我无法确认这一点。

如果我将作用域枚举类移到模板之外,一切都会恢复正常。通过这种方式,我可以简单地向我的实际代码添加一个间接级别,但我不希望这样做。

Here is a godbolt with a macro allowing you to change between the templated and non-templated definition,and a simple main printing out one of the strings

更奇怪的是:假设我将内部数组的类型更改为 ints。即,

struct STRUCTURE {
    enum class ENUM { A,C };
    static constexpr int INTS[] {
        [static_cast<int>(ENUM::A)] = 65,[static_cast<int>(ENUM::B)] = 66,[static_cast<int>(ENUM::C)] = 67
    };

    constexpr int operator[](ENUM e) const {
        return INTS[static_cast<int>(e)];
    }
};

我也有同样的问题。但是现在,如果我通过枚举的静态转换分配值作为指示符,即

...
    static constexpr int INTS[] {
        [static_cast<int>(ENUM::A)] = static_cast<int>(ENUM::A),[static_cast<int>(ENUM::B)] = static_cast<int>(ENUM::B),[static_cast<int>(ENUM::C)] = static_cast<int>(ENUM::C)
    };
...

无论模板与否,这都有效。 Godbolt for this,too

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。