Reputation: 9963
I have an overloaded operator<<
for std::chrono::duration
. As I understand it I have to put that in the std::chrono
namespace so ADL works. However, for some reason when I do that all other references to std::chrono::duration
get marked as ambiguous
by VSCode. This might just be a VSCode bug but it uses clangd
to do correctness checking so I'm wondering if there is actually something wrong with my code. It does compile but VSCode isn't using exactly the same clang
as I'm compiling with so maybe mine is just more permissive?
The smallest example I could come up with is:
#include <chrono>
#include <iostream>
// marks chrono as ambiguous
using std::chrono::milliseconds;
namespace std {
namespace chrono {
// again marks chrono as ambiguous
template <class U, class T>
std::ostream& operator<<(std::ostream& os, const typename ::std::chrono::duration<U, T>& dur) {
os << "foo";
return os;
}
} // namespace chrono
} // namespace std
namespace example {
void DoThing() {
// NOT marked as ambiguous
milliseconds x(10);
// Says no match for operator<< and milliseconds
std::cout << x;
}
} // namespace example
Does it look to anyone like this isn't valid C++ or is this more likely a clangd
or VSCode bug?
Upvotes: 1
Views: 981
Reputation: 180998
Your code is illegal and has undefined behavior. You are not allowed to add your own functions into the std
namespace. The only things you are allowed to add to it are function template specializations (untill C++20) and class template specializations of your own types.
Some further advice: You should not overload operators for types you do not own. If the owner of that type decides to add one themselves, then you could/will have an ODR (One Definition Rule) violation and those require no diagnostic from the compiler so it can lead to very hard to find bugs. If you want to extend the functionality, make your own named function in your own namespace.
Upvotes: 4