简体   繁体   中英

Template class in C++

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!

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.

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.

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