【发布时间】:2014-09-26 10:33:16
【问题描述】:
当我尝试编译这个测试程序时:
struct comma_guard
{
template<class T>
const comma_guard& operator,(T&&) const
{
return *this;
}
};
struct foo {};
template<class T> T operator,(T x, foo)
{
return x;
}
int main()
{
(comma_guard(), foo());
}
我在 clang 上得到一个编译错误:
comma_guard.cpp:20:19: error: use of overloaded operator ',' is ambiguous (with operand types 'comma_guard' and 'foo')
(comma_guard(), foo());
~~~~~~~~~~~~~^ ~~~~~
comma_guard.cpp:6:24: note: candidate function [with T = foo]
const comma_guard& operator,(T&&) const
^
comma_guard.cpp:13:21: note: candidate function [with T = comma_guard]
template<class T> T operator,(T x, foo)
^
这在 gcc 上编译得很好。根据我对 ADL 查找的理解,comma_guard 中的成员函数应该是首选的,因此不应该模棱两可。它是否正确?这是clang中的错误吗?另外,是否有解决方法使comma_guard 中的运算符始终是首选?
更新:所以当它被模板化时,clang 似乎并不认为它是一个类成员。因此,如果我这样定义comma_guard,它将起作用:
struct comma_guard
{
struct any
{
template<class T>
any(T&&);
};
const comma_guard& operator,(any) const;
};
根据 C++,哪个是正确的?
【问题讨论】:
-
is there a workaround so that the operator in comma_guard will always be preferred?是的,虽然很丑:(comma_guard().operator,(foo())); -
您的“更新”有效,因为对于需要转换为
any的成员,非成员更适合。 -
@T.C.是的 - 所以它实际上不是一个解决方案
标签: c++ c++11 clang language-lawyer