c++namespaces

C++: Use of namespaces in program logic / conditional namespaces?


this is a technical question as well as (if it's technically feasible) a style question. In my code I have a series of functions that load and manipulate a file. For different syntax these functions exist in separate namespaces, so that:

namespace typeA {
  void load();
  void manipulate();
};

namespace typeB {
  void load();
  void manipulate();
};

In this minimal example, obviously I could simple have a clause that checks for the file type and then calls typeA:load() and typeB:load() etc. as required.

However, I was wondering if it is also possible to do this using namespace aliases? It would make the code cleaner as there are several dozen calls to functions in the namespaces which all would need a separate if/else clause.

What I've tried:

namespace my_type = (ft == "type_A") ? typeA : typeB;
...
my_type::load();

which doesn't compile with an error in the namespace alias assignment line.

Is there another way of doing this / what is the generally accepted clean way of handling situations like this?

I suppose a virtual class and inheritance for each file type would be one option. Are there others?


Solution

  • There is no way to do such namespace alias.

    3.4.6 Using-directives and namespace aliases [basic.lookup.udir] 1 In a using-directive or namespace-alias-definition, during the lookup for a namespace-name or for a name in a nested-name-specifier only namespace names are considered.

    You an use partial template specialization to solve that.