我发现一个奇怪的行为,当使用G++(gcc 4.8.1,MinGW 4.8.2和-std=gnu++1y
标志)编译我的代码时。为了遵循SSCCE的精神,我把以下代码段隔离了出来:
struct C
{
template< typename X >
auto
f(X &&) const &
{ ; }
template< typename X >
auto
f(X &&) &
{ ; }
template< typename X >
auto
f(X &&) &&
{ ; }
};
int main()
{
int i{};
#if 1
C{}.f(i);
#endif
#if 1
C c{};
c.f(i);
#endif
return 0;
}
它会产生一个错误:
main.cpp: In function 'int main()':
main.cpp:29:10: error: call of overloaded 'f(int&)' is ambiguous
c.f(i);
^
main.cpp:29:10: note: candidates are:
main.cpp:6:5: note: auto C::f(X&&) const & [with X = int&]
f(X &&) const &
^
main.cpp:11:5: note: auto C::f(X&&) & [with X = int&]
f(X &&) &
^
main.cpp:16:5: note: auto C::f(X&&) && [with X = int&]
f(X &&) &&
^
但是在#if 1
和#if 0
或者#if 0
和#if 1
的情况下,编译可以正常进行。如果将所有的auto
替换为void
,则所有内容也可以成功编译。
这是一个Bug还是我的误解?
中,
T&&`实际上充当“通用”引用而不是右值引用。实际的推导规则对我来说非常令人困惑。 - IdeaHatX &&
的出现替换为X const &
,那么一切都保持不变。 - Tomilov Anatoliy