我的团队有一个概念的内部实现,我们遇到了 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/