Search code examples
c++scopenamespacestraitsusing

How to group typedefs (using declarations) and constants common to a bunch of classes and using them inside?


I am trying to find a way to group the main types and constants used by my project into a namespace, and then I'd like to import them in all my classes with "using namespace". I can't figure out why this piece of code doesn't compile, g++ error says:

expected nested-name-specifier before 'namespace'

What options do I have to have all my types and constants grouped together? I tried making Traits a struct and then using inheritance but this gives problems with templates, another way is writing in all classes something like:

using scalar_t = Traits::scalar_t;

Thanks for any tip.

#include <iostream>

namespace Traits {
  constexpr int N = 3;
  using scalar_t = double;
};

struct Entity {
  using namespace Traits; // problems here
  scalar_t foo() const;
  int n = N;
};

scalar_t Entity::foo() const { return N; } // problems here

int main()
{
  Entity e;
  e.foo();

  return 0;
}

Solution

  • The language doesn't actually allow you to import a namespace at class scope. You can solve this by adding another level of indirection, viz. wrapping your class in a namespace, where you can of course import other namespaces.

    namespace Indirection 
    { 
       using namespace Traits;  // ok at namespace scope
                                // now everything from Traits is avaliable
       struct Entity 
       {
          scalar_t foo() const;  // scalar_t is visible, yay!
          int n = N;
       };
    
       scalar_t Entity::foo() const { return N; }  // also ok, since in same namespace
    }
    

    Of course, you don't want to ever have to mention the Indirection namespace again, so you can just lift the Entity out of that namespace.

    using Indirection::Entity;
    

    and now it's as if Indirection never existed at all.

    Here's a demo.