Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an object of template class

I have a template class defined :

 template <class T>
    class TempClass
    {
    ...
    };

If I want to make an object of this class in let's say some MyClass.h to access functions of template class, how shall I pass the argument of the template? I tried to do the following:

class MyClass{
public:
    TempClass<T> temp;
}

Sure, as supposed it does not work, as T is not defined in MyClass, so I am a bit lost how do it correctly.

Thanks.

like image 356
Mike Avatar asked Nov 03 '25 12:11

Mike


1 Answers

If you want MyClass to be a template as well, you would do it like this:

template<typename T>
struct MyClass {
    TempClass<T> temp;
};

(You could also use class instead of struct, but since all members are public, you don't really need default private.)

If you don't want MyClass to be a template, you will need some concrete type to substitute in for T. For example:

struct MyClass {
    TempClass<string> temp;
};

Pedantic: Technically TempClass isn't a template class, it's a class template. A class template isn't actually a class, it's a template that can be used to create individual classes that are themselves template classes. Thus, TempClass is a class template, while TempClass<string> is a template class --- a class that is created by instantiating a template.

like image 108
Adam H. Peterson Avatar answered Nov 06 '25 02:11

Adam H. Peterson