如何在不复制此代码的情况下将一些代码放入多个命名空间? [英] How do I put some code into multiple namespaces without duplicating this code?

查看:82
本文介绍了如何在不复制此代码的情况下将一些代码放入多个命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在两个不同的命名空间中定义了该方法:

Assume I have the method defined in the two different namespaces:

namespace foo
{
    void print()
    {
        //do work...
    }
}

namespace bar
{
    void print()
    {
        //do work...
    }
}

foo::print()bar::print()函数完全相同.我的项目使用了这些功能的大量调用.

The foo::print() and the bar::print() functions are absolutely equal. My project uses the numerous calls of these functions.

是否可以在不更改这些函数调用的情况下删除print()定义之一??我的意思是类似以下内容(当然,C ++语言不允许这种构造,只是一个示例):

Is there a way to remove one of the print() definitions without changing the calls of these function? I mean something like the following (of course, C++ language doesn't allow this construction, it's just an example):

namespace foo, bar  //wrong code!
{
    void print()
    {
        //do work...
    }
}

如果无法根据需要重构代码,请告诉我,您喜欢以下决定吗?如果您的项目包含这样的代码,您会感到高兴吗? :)

If there is no way to refactor the code as I want, please tell me, do you like the following decision? Will you be glad if your project contains such code? :)

namespace foo
{
    void print()
    {
        //do work...
    }
}

namespace bar
{
    void print()
    {
        foo::print();
    }
}

添加:

谢谢大家,我对您的回答感到非常满意.我想请您澄清一下:using ::foo::printusing foo::print之间有区别吗?

Thank you guys, I'm fully satisfied by your answers. Just one moment I want you to clarify: is there a difference between using ::foo::print and using foo::print?

推荐答案

您可以使用using声明来实现.

You can achieve this with a using declaration.

namespace foo
{
    void print()
    {
        //do work...
    }
}

namespace bar
{
    using foo::print;
}

编辑

关于::foo::printfoo::print之间的区别:在限定名称前加上::意味着您在全局名称空间中显式引用了该名称.即使存在另一个名称更接近范围的项,也可以使用它来选择全局项.

Regarding the difference between ::foo::print and foo::print: prepending a qualified name with :: means that you explicitly refer to the one in the global namespace. This can be used to select the global one, even if there is another item with the same name closer in scope.

这篇关于如何在不复制此代码的情况下将一些代码放入多个命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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