Implicit conversion yields "error: taking address of temporary" (GCC vs clang)
Implicit conversion yields "error: taking address of temporary" (GCC vs clang)
在试验强类型整数时,我遇到了一个来自 GCC 8.2 的奇怪错误:
error: taking address of temporary
我可以想象上述错误有意义的典型场景,但在我的情况下我没有遇到问题。重现错误的缩小(人为)示例如下:
#include <cstddef>
#include <type_traits>
enum class Enum : std::size_t {};
struct Pod {
std::size_t val;
constexpr operator Enum() const {
return static_cast<Enum>(val);
}
};
template<std::size_t N>
constexpr void foo() {
using Foo = std::integral_constant<Enum, Pod{N}>;
// [GCC] error: taking address of temporary [-fpermissive]
}
int main() {
foo<2>();
}
为什么 GCC 8.2 在这里抱怨? Clang 6.0 很高兴 (see goldbolt.org)。
请注意,GCC 有第二个错误,可能有助于分析问题。我也不明白:
error: no matching function for call to Pod::operator Enum(Pod*)
GCC 8.2 的完整输出如下
<source>: In instantiation of 'constexpr void foo() [with long unsigned int N = 2]':
<source>:22:10: required from here
<source>:17:50: error: taking address of temporary [-fpermissive]
using Foo = std::integral_constant<Enum, Pod{N}>;
^
<source>:17:50: error: no matching function for call to 'Pod::operator Enum(Pod*)'
<source>:10:13: note: candidate: 'constexpr Pod::operator Enum() const'
constexpr operator Enum() const {
^~~~~~~~
<source>:10:13: note: candidate expects 0 arguments, 1 provided
Compiler returned: 1
这显然是一个错误; 'Pod::operator Enum(Pod*)'
是废话。您不能将参数传递给 operator Enum
.
编译器似乎认为在编译时将 Foo
转换为 Enum
的正确操作是 foo.operator Enum(&foo)
之类的。这都解释了 "address of temporary" 和下一行。
在试验强类型整数时,我遇到了一个来自 GCC 8.2 的奇怪错误:
error: taking address of temporary
我可以想象上述错误有意义的典型场景,但在我的情况下我没有遇到问题。重现错误的缩小(人为)示例如下:
#include <cstddef>
#include <type_traits>
enum class Enum : std::size_t {};
struct Pod {
std::size_t val;
constexpr operator Enum() const {
return static_cast<Enum>(val);
}
};
template<std::size_t N>
constexpr void foo() {
using Foo = std::integral_constant<Enum, Pod{N}>;
// [GCC] error: taking address of temporary [-fpermissive]
}
int main() {
foo<2>();
}
为什么 GCC 8.2 在这里抱怨? Clang 6.0 很高兴 (see goldbolt.org)。
请注意,GCC 有第二个错误,可能有助于分析问题。我也不明白:
error: no matching function for call to
Pod::operator Enum(Pod*)
GCC 8.2 的完整输出如下
<source>: In instantiation of 'constexpr void foo() [with long unsigned int N = 2]':
<source>:22:10: required from here
<source>:17:50: error: taking address of temporary [-fpermissive]
using Foo = std::integral_constant<Enum, Pod{N}>;
^
<source>:17:50: error: no matching function for call to 'Pod::operator Enum(Pod*)'
<source>:10:13: note: candidate: 'constexpr Pod::operator Enum() const'
constexpr operator Enum() const {
^~~~~~~~
<source>:10:13: note: candidate expects 0 arguments, 1 provided
Compiler returned: 1
这显然是一个错误; 'Pod::operator Enum(Pod*)'
是废话。您不能将参数传递给 operator Enum
.
编译器似乎认为在编译时将 Foo
转换为 Enum
的正确操作是 foo.operator Enum(&foo)
之类的。这都解释了 "address of temporary" 和下一行。