简体   繁体   中英

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.

C ++语法/规范指出,只要存在一个合格名称,该合格名称可能是类型或变量(即使在typedef上下文中),除非将其前缀为typename ,否则它将始终被视为变量。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM