Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template class in C++

Tags:

c++

templates

We have following class definition

template<typename T>
class Klass {...}

and we also have below two instantiations

Klass<int> i;
Klass<double> d;

how many copies of Klass' methods are generated by the C++ compiler? Can somebody explain it? Thanks!

like image 769
eleven Avatar asked Aug 15 '26 09:08

eleven


2 Answers

Klass isn't a type, so it doesn't make sense to talk of Klass's methods. Kalss<int> is a type with it's own methods, and so is Klass<double>. In your example there would be one set of methods for each type.

Edit in real life, it isn't as simple as that. The question of the actual existence of the methods also depends on other factors, see @KerrekSB's answer to this question.

like image 183
juanchopanza Avatar answered Aug 16 '26 23:08

juanchopanza


Each template instance is an entirely separate, distinct and independent type of its own. However, the code for class template member functions is only generated if the member function is actually used for a given template instantiation (unless you instantiate the template explicitly for some set of parameters). Among other things, this means that if some class template member function's body doesn't actually make sense for a given template parameter, then you can still use the overall template as long as you don't invoke that member function, since the code for the member function will never get compiled.

Also bear in mind that templates can be specialized:

template <typename T> struct Foo {
    int bar;
    void chi();
};

template <> struct Foo<int> {
    double bar(bool, char) const;
    typedef std::vector<bool> chi;
    bool y;
};

As you can see, there's a lot you cannot just tell from a template itself until you see which actual instantiations you'll be talking about.

like image 23
Kerrek SB Avatar answered Aug 16 '26 21:08

Kerrek SB