简体   繁体   English

C ++中的模板类

[英]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? C ++编译器生成了多少个Klass方法的副本? Can somebody explain it? 有人可以解释一下吗? Thanks! 谢谢!

Klass isn't a type, so it doesn't make sense to talk of Klass 's methods. Klass不是一个类型,所以谈论Klass的方法是没有意义的。 Kalss<int> is a type with it's own methods, and so is Klass<double> . Kalss<int>是一个有自己方法的类型, 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. 这些方法的实际存在问题也取决于其他因素,请参阅@ KerrekSB对此问题的回答。

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. 正如您所看到的,在您看到您将要讨论的实际实例之前,您可以从模板本身中分辨出很多内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM