ADL与来自另一个命名空间的typedef [英] ADL with typedefs from another namespace

查看:187
本文介绍了ADL与来自另一个命名空间的typedef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的:

#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;
}

这自然不起作用,因为ADL不会找到 operator ,因为命名空间N 未与 MyPair )。 Afaik不能添加到命名空间std中,所以如果我选择在std中定义运算符<< 这将是非法的。所以...在这种情况下要做什么?我不想显式限定运算符< ,也不希望使用命名空间N 。因此,问题是:

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. 如何重构代码?

  2. typedefs的命名空间?严重的原因?这将是很好,例如。在这种情况下。感谢


推荐答案


  1. 在命名空间N中,可能继承自std :: pair。你可以添加using namespace N;里面主。

  1. You could create your own type in namespace N, possibly inheriting from std::pair. You could add "using namespace N;" inside main. The former is more likely to be useful.

因为类型在另一个命名空间中定义,不能在两个中定义。

Because the type is defined in another namespace and cannot be defined in two.

示例:

namespace N { 
struct MyPair : std::pair<int, double> {
  MyPair(int first, double second) : std::pair<int, double>(first, second) {}
  // add defaults if desired: first=0, second=0.0
  // with defaults, you may want to make the ctor explicit or leave implicit

  // also, if desired and you don't use two defaults above:
  MyPair() : std::pair<int, double>(0, 0.0) {}

  // in 0x, you can "import" the base's ctors with a using declaration
};
}

如果用作std :: pair不重要,删除继承并重命名成员。在任何一种情况下,你当然可以添加额外的方法,但如果你保留继承,你可以使用重命名方法:

If being used as a std::pair isn't important, you can drop the inheritance and rename the members. In either case you can, of course, add additional methods, but if you keep the inheritance you can use "renaming methods":

int      & foo()       { return first; }
int const& foo() const { return first; }
double      & bar()       { return second; }
double const& bar() const { return second; }

这篇关于ADL与来自另一个命名空间的typedef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆