Demod
Demod

Reputation: 53

Can a class be used as generic namespace (using templates)?

I have a namespace with several functions I use with a class that was already defined

class Object {
    struct SubObject{
        //...
    };
    //...
};


namespace Process
{
    Object::SubObject function1(Object& o){
        //..        
    }

    void function2(Object& o){
        //..
    }
}

Now, I have to generalize those functions with a template, I've noticed I cannot use one template over an entire namespace. Either I have to make a template for each functions (rather tedious considering I have to typedef each struct of the class each time), or I would like to know if I can do something like defining a class instead of a namespace :

template<typename TObject>
class Process
{
    typedef typename TObject::SubObject TSubObject;

    TSubObject function1(TObject& o){
        //..        
    }

    void function2(TObject& o){
        //..
    }
}

Is that correct code ? It seems strange to make a class I will never instanciate.

Also, I first wrote :

typedef TObject::SubObject TSubObject;

But my compiler asked me to add typename in front of TObject, I found this question explaining (or that's how I understood it) that it was because the compiler doesn't know if SubObject is a nested type or an member variable. But isn't typedef obligatorily followed by a type, then an alias ? I thought a class member (a variable or a function) cannot be "typedef"ed.

Thank you in advance for your answers.

Upvotes: 0

Views: 273

Answers (1)

Mark B
Mark B

Reputation: 96301

The C++ grammar/specification states that any time there is a qualified name that may be a type or a variable (even in say a typedef context), it will always be considered as a variable unless you prefix it with typename.

Upvotes: 0

Related Questions