加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用constexpr initializer_list构造函数时,MSVC无法编译

发布时间:2020-12-16 10:05:54 所属栏目:百科 来源:网络整理
导读:为什么Microsoft Visual C在编译以下代码时失败? : template typename Tstruct slice{ size_t length; T *ptr; constexpr slice(std::initializer_listT list) : length(list.size()),ptr(list.begin()) {}};static_assert(sliceconst int({ 1,2,3 }).leng
为什么Microsoft Visual C在编译以下代码时失败? :

template <typename T>
struct slice
{
    size_t length;
    T *ptr;

    constexpr slice(std::initializer_list<T> list)
        : length(list.size()),ptr(list.begin()) {}
};

static_assert(slice<const int>({ 1,2,3 }).length == 3,"!!");

我得到的错误是:

1>test.cpp(12): error C2131: expression did not evaluate to a constant
1>         visual studio 14.0vcincludeinitializer_list(50): note: failure was caused by an undefined arithmetic operation

initializer_list的实现具有标记为constexpr的所有方法,看起来它对我来说应该没问题……也许它只是一个编译器问题?

解决方法

TL; DR:这是一个编译器标准问题,因为你的代码编译好,gcc 6.3.1和 clang 3.9.1都编译你的代码.

在C 11中,没有一个方法标记为constexpr,因此您不能在static_assert中使用它.

您必须注意Visual Studio 2015没有完整的constexpr支持.请参阅文章中的the C++ 14 Core Language Features
表.它只实现了st 11 :: initializer_list的C 11版本,它没有任何constexpr函数.

小更新:看起来标准中的错误措辞会导致非常量的std :: initializer_list:

From § 18.9.2 (emphasis mine):

An object of type initializer_list<E> provides access to an array of objects of type const E. [Note: A pair of pointers or a pointer plus a length would be obvious representations for initializer_list. initializer_list is used to implement initializer lists as specified in 8.5.4. Copying an initializer list does not copy the underlying elements.
—end note]

So there is no requirement for the private members of the implementation of initializer_list to be non-volatile literal types; however,because they mention that they believe a pair of pointers or a pointer and a length would be the “obvious representation,” they probably didn’t consider that someone might put something non-literal in the members of initializer_list.

(从this回答无耻地复制.)它更深入,关于为什么你不能在constexpr上下文中使用std :: initializer_list.

这已在Visual Studio 2017中“修复”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读