[cfe-dev] Templated operator overloading
antoni at buszta.info
antoni at buszta.info
Thu May 22 01:12:47 PDT 2014
Hi all,
I have some small problem with clang behavior in such code:
struct stream
{
stream() {}
template<typename T>
inline stream& operator<<(T& t)
{
return *this;
}
};
template<typename Stream>
inline Stream& operator<<(Stream& stream, int& t)
{
return stream;
}
int main(int argc, char *argv[])
{
int i = 42;
stream a;
a << i;
return 0;
}
This code compiles fine under clang (I have checked with 3.4 and current
trunk) and gcc. However when I add -std=c++11 it still compiles fine
under gcc but it stops compiling under clang. Error is:
/home/abuszta/Development/llvm/bin/clang++ -std=c++11 operator.cpp
-o operator
operator.cpp:21:7: error: use of overloaded operator '<<' is ambiguous
(with operand types 'stream' and 'int')
a << i;
~ ^ ~
operator.cpp:5:20: note: candidate function [with T = int]
inline stream& operator<<(T& t)
^
operator.cpp:12:16: note: candidate function [with Stream = stream]
inline Stream& operator<<(Stream& stream, int& t)
^
1 error generated.
In order to answer the question which behavior is good and which is bad
I tried to find appropriate section in C++ standard. After analyzing
14.5.6.2 (section about Partial ordering of function templates in N3337)
and related I think there should not be any ambiguity after substitution
and function should be choosed...
What is more, when I make const stream a; this code compiles fine even
with -std=c++11 and chooses the standalone function in favor to member
function which suggests that there may be some problem with template
resolution here.
What is your interpretation of this behavior? Should I report bug?
Best regards,
Antoni Buszta.
More information about the cfe-dev
mailing list