Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an inner class of a template class be a non-template class?

I am making a template class with an inner utility class. All specializations of the template want the same inner class:

template<...> class Outer {
    class Inner { };
};

That gives me Outer<...>::Inner but I want all Inner to be the same type, as if I'd just written:

class Inner { };
template <...> class Outer { };

or if Outer were simply not a template class:

class Outer {
    class Inner { };
};

giving me Outer::Inner. I'd like to have Outer::Inner work for all Outer<> if that's possible (just for namespace/clarity reasons). Otherwise of course I can just move Inner out.

like image 744
Ben Jackson Avatar asked Jul 19 '11 21:07

Ben Jackson


People also ask

Can a template method be a member of a non template class?

It's not the method that is templated, it's the class. You can have a templated method in a non-templated class, a non-templated method in a templated class (your case) and a templated method in a templated class, and of course a non-templated method in a non-templated class. Save this answer.

Can a template class inherit from another template class?

It is possible to inherit from a template class. All the usual rules for inheritance and polymorphism apply. If we want the new, derived class to be generic it should also be a template class; and pass its template parameter along to the base class.

What is the difference between class template and template class?

An individual class defines how a group of objects can be constructed, while a class template defines how a group of classes can be generated. Note the distinction between the terms class template and template class: Class template. is a template used to generate template classes.

Can classes can be defined as templates?

Classes can be defined as templates. In a template function definition, all parameters must be of the template class (T). If you define a function template, then the compiler will create a separate function definition for every data type that exists.


1 Answers

The nested class can be a non-template, but every instantiation of the template will have its own nested class because they're (otherwise) unrelated types. You can do

namespace detail {

class Inner {};

} // detail

template<...>
class Outer {
    typedef detail::Inner Inner;
};
like image 112
Luc Danton Avatar answered Sep 27 '22 23:09

Luc Danton