0

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.

Community
  • 1
  • 1
Demod
  • 53
  • 1
  • 1
  • 8
  • You can't call the functions in your sample without an instance, you'll need to make them `static` functions then! Another option is to simply provide templated functions at the namespace level. – πάντα ῥεῖ Jan 14 '14 at 17:04
  • @πάνταῥεῖ : Yes but I would have to make a template for each functions in the namespace, and make a typedef for each nested type in each function (I have like a dozen of nested type in Object, I would like to avoid doing typedef/typename every time). – Demod Jan 14 '14 at 17:09
  • Then use the other option with static functions in a templated class. – πάντα ῥεῖ Jan 14 '14 at 17:11

1 Answers1

0

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.

Mark B
  • 95,107
  • 10
  • 109
  • 188