Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

c++ - ADL with typedefs from another namespace

I have something like this:

#include <iostream>
namespace N
{
   typedef std::pair<int, double> MyPair;
   std::ostream& operator << (std::ostream& o, MyPair const & mypair)
   {
      ///
   }
}

int main()
{
    N::MyPair pr;
    std::cout << pr;
}

This naturally doesn't work, because ADL won't find operator<< because namespace N is not associated with MyPair (unfortunately). Afaik one may not add to namespace std, so if I chose to define operator << in std that would be kinda illegal. So... what to do in such situations? I don't want to explicitly qualify operator <<, nor do I wish to write using namespace N. So, questions are:

  1. How to refactor the code?
  2. Why wouldn't ADL associate namespaces of typedefs? Serious reasons? It would be nice, e.g. in this case. Thanks
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I can't think of a reason why typedef names should not participate in ADL. Furthermore, it makes the following code implementation defined :

#include <algorithm>
#include <vector>

namespace my {
class A {};
void for_each();
} // my

int main()
{
    std::vector<my::A> v;
    for_each(v.begin(), v.end(), [...]);
} 
  • If std::vector<T>::iterator is a typedef for something which sits in the std namespace : std::for_each will be called
  • If std::vector<T>::iterator is a typedef for my::A * : the compiler should complain that my::for_each doesn't take 3 arguments

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...