Do C ++模板类为每个使用的指针类型重复代码? [英] Do C++ template classes duplicate code for each pointer type used?

查看:148
本文介绍了Do C ++模板类为每个使用的指针类型重复代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我的理解,如果你有,例如, std :: vector< int> std :: vector< float> ; ,编译器创建两个类,每个类型一个。因此,尽管减少了编写的代码量,但是你不会减少可执行文件的大小(如果我错了,请纠正我)。



即使类型是一个指针?例如,将实例化 std :: vector< SomeClass *> std :: vector< SomeOtherClass *> 必须使编译器为两个实例的每一个生成单独的代码?

解决方案

模板作为您的程序使用。



实际上,在上执行的大多数操作,向量将被内联。因此,根据从该模板实例化多少不同的类,可执行大小可能不会很大地改变,因为大部分代码大小是每个函数调用站点而不是每个不同的类。但是,取决于实例化的数量,向量< SomeClass *> 向量< SomeOtherClass *> 如果你做一个明确的实例化向量,那么全部 em>成员函数将为类生成。你可能会看到代码大小的差异,如果你寻找它。但通常你没有显式实例化模板类,因此只生成你使用的成员函数。


From what I understand, if you have, for example, an std::vector<int> and an std::vector<float>, the compiler creates two classes, one for each type. Thus, although you reduce the amount of code written, you do not reduce executable size (correct me if I'm wrong).

Is the same true even if the type is a pointer? For example, would instantiating an std::vector<SomeClass*> and an std::vector<SomeOtherClass*> necessarily cause the compiler to generate separate code for each of the two instantiations?

解决方案

The compiler instantiates as many classes from the template as your program uses. Code generated to go in your executable is a slightly different matter, though, from what classes exist in your program.

In practice, most operations on vector will be inlined. So the executable size probably doesn't change very much according to how many different classes are instantiated from that template because the bulk of the code size is per function call site rather than per distinct class. But as far as it does depend on the number of instantiations, vector<SomeClass*> and vector<SomeOtherClass*> are different classes.

If you do an explicit instantiation of vector, then all the member functions will get generated for the class. You'll probably see that difference in code size, if you look for it. But normally you don't explicitly instantiate template classes, and so only the member functions you use are generated.

这篇关于Do C ++模板类为每个使用的指针类型重复代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆