constexpr函数中的For循环无法使用MSVC 19.23进行编译

问题描述 投票:1回答:1

以下代码在Clang和GCC中编译,但在MSVC中失败。

template <typename... FieldsSequence>
struct S {
    static constexpr bool checkIdUniqueness()
    {
        using IdType = int;
        constexpr IdType fieldIds[sizeof...(FieldsSequence)]{ 0 };
        for (size_t i = 0; i < std::size(fieldIds) - 1; ++i)
        {
            if (fieldIds[i] > fieldIds[i + 1])
            {
                constexpr auto tmp = fieldIds[i];
                fieldIds[i] = fieldIds[i + 1];
                fieldIds[i + 1] = tmp;
            }
        }

        return true;
    }
};

错误消息是:

expression did not evaluate to a constant
note: failure was caused by a read of a variable outside its lifetime
note: see usage of 'i'

是否有一种方法可以使这三个编译器一起使用?最终,我需要对数组进行冒泡排序,以便在编译时断言所有值都是唯一的。

https://godbolt.org/z/9XbP6-

c++ for-loop c++17 constexpr compile-time
1个回答
0
投票

您过度使用了constexpr声明。例如,如果将fieldIds声明为constexpr,则它也是const,并且您无法对其进行突变。至于tmp,因为已声明为constexpr,所以初始化程序必须是一个常量表达式,但实际上不是一个常量表达式。

© www.soinside.com 2019 - 2024. All rights reserved.