C++ – Dynamic namespace usage based on a template parameter

boostcnamespacestemplatestypedef

I don't know if that is feasable at all, but this is what I'd like to achieve : in a templated class I would like to be using the namespace of the template parameter.

eg.

template<class P>
class Foo
{
    public:
        Foo();
        virtual ~Foo();

        void doSomething(P&);
        void doSomethingElse();

    protected:
        // There I'm hardcoding "namespace1" but that's what I'd like to 
        // be possibly dynamic 
        // (I'm assuming template parameter P = namespace1::Type)
        void method1(namespace1::Type1&);
        ...
        void methodN(namespace1::TypeN&);
}

// Again, supposing P == namespace1::Type then I want to be using namespace1 
// everywhere in the implementation...
using namespace namespace1;

template<class P>
void Foo<P>::doSomething(P& parameter)
{
    ...
    Type1 type1 = P.getType1(); // There namespace1::Type1 is returned !!
    method1(type1);
    ...
}

template<class P>
void Foo<P>::doSomethingElse()
{
    ...
    TypeN typen; // There I want to instanciate a namespace1::TypeN !!
    ...
}

...

Of course I don't want to specialize the template and provide a dedicated implementation for every possible P value as well as I'd like to avoid passing all the types like Type1 and TypeN as template parameters since I potentially have lots of them.

Is that possible ?

The project is C++3 based, any boost solution is welcome.

Update

Being the template parameter P itself exactly like any TypeN parameter, this could be the right approach :

template<typename NAMESPACE>
class Foo
{
    typedef typename NAMESPACE::Parameter MyParameter; 
    typedef typename NAMESPACE::Type1 MyType1; 
    typedef typename NAMESPACE::Type1 MyTypeN; 
    ...
}

Best Answer

Yes and No.

Yes it is possible to deduce secondary types from a primary one, generally using a trait system:

template <typename T> struct Trait { typedef typename T::Secondary Secondary; };

template <typename X>
struct Foo {
    typedef typename Trait<X>::Secondary Secondary;

    void foo(Secondary const& s);
};

No, you cannot deduce a namespace, and thus cannot use it; but note how by using a local alias (typedef ...) within the class there is no need to.