How do I put some code into multiple namespaces without duplicating this code?

Viewed 573

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

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

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

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

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();
    }
}

ADD:

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?

5 Answers
Related