为什么命名空间组成这么少使用? [英] Why is namespace composition so rarely used?

查看:68
本文介绍了为什么命名空间组成这么少使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在他的书 C ++编程语言(第三版)中,Stroustrup教会在自己的命名空间中定义各个组件,并将它们导入到一般的命名空间中。



例如:

 命名空间array_api {
struct array {};
void print(const array&){}
}

命名空间list_api {
struct list {};
void print(const list&){}
}

命名空间api {
使用array_api :: array;
using list_api :: list;
}



我看起来很有趣,但我从来没有见过这种方法。 / p>

为什么这种技术几乎从不使用?

解决方案

不知道什么好处(如Raymond Chen所说,每个功能从-100点开始)。然而,我有一个对立点提供:Luabind,它使用的东西,看起来像这样。请参见 luabind / object.hpp ,其中实质上说:

  namespace luabind {
namespace adl {
class object {
};
}
使用adl :: object;
}



从这个名字我们可以推断出动机: 。给定用户知道的 luabind :: object (实际上是 luabind :: adl :: object 相关函数将由编译器从 luabind :: adl 命名空间中自动发现。然而,这些函数,用户可能不需要以非常明确的方式知道,不污染主要的 luabind 命名空间。所以这很好,我猜。



但你知道什么不好吗?转发声明这些类之一。这失败:

  namespace luabind {class object; } 

您需要这样做:

  namespace luabind {namespace adl {class object; }} 

因此,抽象会迅速泄露,因为用户需要知道这个魔法 adl 命名空间。


In his book The C++ Programming Language (third edition) Stroustrup teaches to define individual components in their own namespace and import them in a general namespace.

For example:

namespace array_api {    
    struct array {};    
    void print(const array&) { }
}

namespace list_api {
    struct list {};        
    void print(const list&) { }
}

namespace api {
    using array_api::array;
    using list_api::list;
}

I looks interesting, but I have never seen this approach used in practice.

Why is this technique is almost never used?

解决方案

Mostly I wonder what the benefits would be (as Raymond Chen says, every feature starts with -100 points). However, I have a counterpoint to offer: Luabind, which does use something that looks like this. See luabind/object.hpp, which essentially says:

namespace luabind {
  namespace adl {
    class object {
    };
  }
  using adl::object;
}

From the name alone we can infer the motivation: to support argument-dependent lookup. Given what the user knows as a luabind::object, which is actually a luabind::adl::object, related functions will be discovered automatically by the compiler from the luabind::adl namespace. Yet those functions, which the user may not need to know about in a very explicit way, do not "pollute" the main luabind namespace. So that's nice, I guess.

But you know what's not nice? Forward declaring one of these classes. This fails:

namespace luabind { class object; }

You need to do this instead:

namespace luabind { namespace adl { class object; } }

Thus the abstraction quickly leaks, as the user does need to know about this magic adl namespace after all.

这篇关于为什么命名空间组成这么少使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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