gpt4 book ai didi

c++ - `static constexpr auto` 使用未命名枚举初始化的数据成员

转载 作者:IT老高 更新时间:2023-10-28 12:54:07 26 4
gpt4 key购买 nike

我正在开发一个 C++11 项目,仅使用 clang++-3.4 ,并决定使用 g++-4.8.2 进行编译以防产生的错误有任何差异。原来g++拒绝了clang++接受的一些代码。我已将问题简化为下面给出的 MWE。


enum { a };

template <class T>
struct foo
{
static constexpr auto value = a;
};

int main()
{
static constexpr auto r = foo<int>::value;
}

foo.cpp:5:23: error: ‘const<anonymous enum> foo<int>::value’, declared using anonymous type, is used but never defined [-fpermissive]

static const auto value = A;

我需要一些帮助来回答以下两个问题:

  • 哪个编译器对标准的解释是正确的?我假设一个编译器在接受或拒绝代码方面是正确的,而另一个是错误的。

  • 我该如何解决这个问题?我无法命名匿名枚举,因为它来自第三方库(在我的例子中,枚举是 Eigen::RowMajorEigen::ColMajor)。

最佳答案

谁的责任?

GCC 错误地拒绝了您的代码段,根据 C++11 标准 (N3337),它是合法的。带有证明和解释的引文位于本文末尾。

解决方法 (A) - 添加缺少的定义

template <class T>
struct foo {
static constexpr auto value = a;
typedef decltype(a) value_type;
};

template<class T>
constexpr typename foo<T>::value_type foo<T>::value;


解决方法 (B) - 使用枚举的底层类型作为占位符

#include <type_traits>

template <class T>
struct foo {
static const std::underlying_type<decltype(a)>::type value = a;
};

标准是怎么说的? ( N3337 )

如上所述,该片段是合法的C++11,可以在以下引用的部分中阅读。


我们什么时候可以使用没有链接的类型?

[basic.link]p8 有详细的措辞来描述一个类型何时是“无链接”,并声明未命名的枚举算作这种类型。

[basic.link]p8 还明确指出了不能使用这种类型的三个上下文,但没有一个上下文适用于我们的使用,因此我们是安全的。

A type without linkage shall not be used as the type of a variable or function with external linkage unless

  • the entity has C language linkage (7.5), or
  • the entity is declared within an unnamed namespace (7.3.1), or
  • the entity is not odr-used (3.2) or is defined in the same translation unit


你确定我们可以在这种情况下使用 auto 吗?

是的,这可以通过以下引用来证明:

7.1.6.4p auto specifier [dcl.spec.auto]

A auto type-specifier can also be used in declaring a variable in the condition of a selection statement (6.4) or an iteration statement (6.5), in the type-specifier-seq in the new-type-id or type-id of a new-expression (5.3.4), in a for-range-declaration, and in declaring a static data member with a brace-or-equal-initializer that appears within the member-specification of a class definition (9.4.2).

关于c++ - `static constexpr auto` 使用未命名枚举初始化的数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24018932/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com