gpt4 book ai didi

c++ - GCC 错误还是 UB?这段代码应该编译吗?

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

下面的代码用 clang 编译得很好,但不能用 GCC 编译。 (试过 4.1.2、4.5.4 和 4.7.2):

template <typename T>
struct A
{
struct B { };
};

template <typename T>
bool operator==(typename A<T>::B const& b, T const& t);

enum { BAR };

template <typename T>
bool test()
{
return 0 == BAR;
}

来自 GCC 4.7.2 的错误消息是:

a.cpp: In instantiation of ‘struct A<<anonymous enum> >’:
a.cpp:12:6: required by substitution of ‘template<class T> bool operator==(const typename A<T>::B&, const T&) [with T = <anonymous enum>]’
a.cpp:19:17: required from here
a.cpp:6:12: error: ‘<anonymous enum>’ is/uses anonymous type
a.cpp:6:12: error: trying to instantiate ‘template<class T> struct A<T>::B’
a.cpp:6:12: error: ‘<anonymous enum>’ is/uses anonymous type
a.cpp:6:12: error: trying to instantiate ‘template<class T> struct A<T>::B’

GCC拒绝代码是正确的,还是我遇到了它的错误?

附:我在尝试构建一个开源项目时看到了这个错误。我试图制作尽可能小的例子来重现它。

最佳答案

根据原始标准,它不是有效的 C++:

标准的14.3.1说:

2 A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template argument for a template type-parameter. [Example: ...

但是我相信最新的 C++11 标准已经取消了这个限制。这或许可以解释为什么有些编译器接受它而其他编译器拒绝它。

关于c++ - GCC 错误还是 UB?这段代码应该编译吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13667057/

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