1

The project calls functions from a library. I want to move those functions behind a namespace so that is easier to spot the places on the codebase where those functions are being called.

How functions are being called:

#include "foo.h"

int main()
{
    foo();
    bar();

    return 0;
}

How I want to call them:

#include "myfoo.h"

int main()
{
    thatlibrary::my_foo();
    thatlibrary::my_bar();

    return 0;
}

How I implemented that:

myfoo.h

namespace thatlibrary
{
    void my_foo();
    void my_bar();
}

myfoo.cpp

namespace thatlibrary
{
    void my_foo()
    {
        foo();
    }

    void my_bar()
    {
        bar();
    }
}

Wondering if there is any other solution? Perhaps more elegant.

Chris
  • 26,361
  • 5
  • 21
  • 42
KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • So this library doesn't wrap all its names in a namespace? :/ – Enlico Sep 08 '22 at 14:03
  • Is the library header-only? That would be an easier case than a library that has a binary component. – JaMiT Sep 08 '22 at 14:11
  • @Enlico the library has no namespace. – KcFnMi Sep 08 '22 at 14:17
  • @JaMiT Why? Anyway, is not header-only (it's .h + .dll) – KcFnMi Sep 08 '22 at 14:18
  • Does this answer your question? [How not to pollute the global namespace with declarations of a C header?](https://stackoverflow.com/questions/33263405/how-not-to-pollute-the-global-namespace-with-declarations-of-a-c-header) – Enlico Sep 08 '22 at 14:24
  • @KcFnMi Because definitions in a header can be moved to a namespace (rather easily), while definitions in a .dll cannot. – JaMiT Sep 09 '22 at 00:18

1 Answers1

1

Just use a using declaration in your namespace:

// global namespace
int foo() {
    return 1;
}

namespace thatlibrary {
    using ::foo;
}

auto i = thatlibrary::foo();

Notice that the name foo is still available in the global namespace, though.

// in global namespace
auto j = foo(); // works just fine
// from anywhere
auto k = ::foo(); // works just fine

I think the library is poorly designed, if it declares all its stuff in the global namespace.

Enlico
  • 23,259
  • 6
  • 48
  • 102