c++ - 这是 GCC 中可能存在的错误吗?

标签 c++ gcc gcc8

我的团队有一个概念的内部实现,我们遇到了 GCC 的错误。以下代码将在 Visual Studio 2019 上运行,但在 GCC 8.3 上失败:

#include <type_traits>
#include <iterator>

template <typename T>
constexpr auto name(int, T &instance = std::declval<T &>()) -> decltype(
    std::declval<decltype(std::begin(instance)) &>(), std::true_type{}) { return {}; }

template <typename>
constexpr auto name(...) -> decltype(std::true_type{}) { return {}; }

auto main() -> int {
    auto&& t =std::declval<nullptr_t>();
    name<nullptr_t>(0);
}

Godbolt 上的 GCC 8.3 和我们的 WSL 安装返回以下错误:

In file included from <source>:1:

/opt/compiler-explorer/gcc-8.3.0/include/c++/8.3.0/type_traits: In instantiation of 'decltype (__declval<_Tp>(0)) std::declval() [with _Tp = std::nullptr_t; decltype (__declval<_Tp>(0)) = std::nullptr_t&&]':

<source>:12:39:   required from here

/opt/compiler-explorer/gcc-8.3.0/include/c++/8.3.0/type_traits:2058:21: error: static assertion failed: declval() must not be used!

       static_assert(__declval_protector<_Tp>::__stop,

                     ^~~~~~~~~~~~~~~~~~~~~~~~

Compiler returned: 1

有什么帮助吗?

最佳答案

实际上,考虑到您正在做的事情,gcc 是这里明智的编译器:

T &instance = std::declval<T &>()

在参数中。如cppreference说:

Note that declval can only be used in unevaluated contexts and is not required to be defined; it is an error to evaluate an expression that contains this function. Formally, the program is ill-formed if this function is odr-used.

所以这是来自 MSVC 的糟糕检查,而不是 GCC 中的错误。 declval 如您所见,完全允许不定义。

关于c++ - 这是 GCC 中可能存在的错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58338312/

相关文章:

c++ - 在 Embedded Octave C++ 中如何执行脚本文件? ("error: invalid call to script")

c++ - 从另一个进程设置 HWND 的 lpfnWndProc

c++ - 在 IsClassT<T> 中,为什么使用 "int C::*"?我对 int 类型感到困惑

c++ - 加载库失败,但引用库中的符号可用

c - GCC asm 内联约束,寄存器分配冲突

c++ - 类内将不完整类型的 unique_ptr 初始化为 nullptr 时,gcc 编译错误

c++ - 如何在 C/C++ 中比较两个二维 char 数组

c - 海湾合作委员会优化?

c++ - 将 std::function 类成员与编译器优化一起使用时出现段错误