小编eor*_*jas的帖子

const 有效但不 constexpr

这是一个让我头疼的问题,但它适用于 const,但不适用于 constexpr,我想知道你们聪明的人是否可以解释一下。用 g++ -std=c++14 编译。

struct Service
{
    std::string name;
    enum {
        thread,
        interrupt,
        end_types
    } que_type;
};

const Service namedServices[] =
{
    {"abc", Service::thread},
    {"efg", Service::thread},
    {"hij", Service::interrupt},
    {"klm", Service::thread},
    {"nop", Service::interrupt},
    {"qrs", Service::thread},
    {"", Service::end_types}
};

constexpr int thcnt()
{
    int cnt = 0;
    for (const Service* sp = namedServices; sp->que_type != Service::end_types; sp++) {
        if (sp->que_type == Service::thread)
            cnt++;
    }
    return cnt;
}
int main(int argc, char** argv)
{
    std::string strs[thcnt()];
 ...
Run Code Online (Sandbox Code Playgroud)

这可以编译并且据我所知是正确的。如果我改为

constexpr Service namedServices[] …
Run Code Online (Sandbox Code Playgroud)

c++ constants constexpr

2
推荐指数
1
解决办法
67
查看次数

标签 统计

c++ ×1

constants ×1

constexpr ×1