Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"templating" a namespace

I'd like to build something like this:

File 1:
template<typename Vector>
namespace myNamespace {
  class myClass1{ myClass1(Vector v) {...} }
}

File 2:
template<typename Vector>
namespace myNamespace {
  class myClass2{ myClass2(Vector v) {...} }
}

Of course this is not possible because you cannot template namespaces. Instead I could use a struct instead of a namespace, but then I cannot spread the namespace functions over several files.

Is there any solution for such a problem?

PS: I know I could template the classes, but then I'd have to specify which vector type I want to use anytime I create a new class.

like image 931
Manuel Avatar asked Jul 23 '10 15:07

Manuel


1 Answers

Following up on your comment:

Instead of writing

using namespace myNamespace<int>;

Just use templated classes and write this instead (or whatever variation):

typedef myNamespace::myClass1<int> myClass1Int;
typedef myNamespace::myClass2<int> myClass2Int;

I tend to think it's better to be explicit about what types are being used rather than trying to do something like import a particular instantiation of a namespace.

Can you more fully describe the problem that makes you think templated namespaces would be useful?

And remember you can always write a make_myClass1 free function to deduce the template type for you.

like image 139
Mark B Avatar answered Sep 19 '22 19:09

Mark B