Saturday 13 July 2019

c++ - Ambiguous operator overload on clang

When I try to compile this test program:


struct comma_guard
{
template
const comma_guard& operator,(T&&) const
{
return *this;
}
};
struct foo {};
template T operator,(T x, foo)
{
return x;
}
int main()
{
(comma_guard(), foo());
}

I get a compile error on 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 T operator,(T x, foo)
^

This compiles fine on gcc. From my understanding of ADL lookup, the member function in comma_guard should be preferred and so therefore shouldn't be ambiguous. Is this correct? Is this a bug in clang? Also, is there a workaround so that the operator in comma_guard will always be preferred?


Update: So it seems clang doesn't consider it a class member when its templated. So if I define the comma_guard like this, it will work:


struct comma_guard
{
struct any
{
template
any(T&&);
};
const comma_guard& operator,(any) const;
};

Which is correct according to C++?

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...