C ++模板:说服自己对代码膨胀 [英] C++ Templates: Convincing self against code bloat

查看:193
本文介绍了C ++模板:说服自己对代码膨胀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说过C ++模板上下文中的代码膨胀。我知道,现代C ++编译器不是这样。但我想建立一个例子,说服自己。

I have heard about code bloats in context of C++ templates. I know that is not the case with modern C++ compilers. But, I want to construct an example and convince myself.

假设我们有一个类

template< typename T, size_t N >
class Array {
  public:
    T * data();
  private:
    T elems_[ N ];
};

template< typename T, size_t N >
T * Array<T>::data() {
    return elems_;
}

此外,让我们说 types.h 包含

typedef Array< int, 100 > MyArray;

x.cpp 包含

MyArray ArrayX;

y.cpp 包含

MyArray ArrayY;

现在,我如何验证 MyArray :: data ()对于 ArrayX ArrayY

Now, how can I verify that the code space for MyArray::data() is same for both ArrayX and ArrayY?

还有什么我应该知道和验证从这(或其他类似的简单)的例子?如果有任何g ++特定的提示,我也对此感兴趣。

What else I should know and verify from this (or other similar simple) examples? If there is any g++ specific tips, I am interested for that too.

PS:关于膨胀,我担心即使是最轻微的膨胀,上下文。

PS: Regarding bloat, I am concerned even for the slightest of bloats, since I come from embedded context.

添加:如果模板类显式实例化,情况是否会发生变化?

Addition: Does the situation change anyhow if the template classes are explicitly instantiated?

推荐答案

你问的是错误的问题 - 你的例子中的任何膨胀与模板无关。 (你的问题的答案,btw,是取两个模块中的成员函数的地址,你会看到他们是一样的)

You're asking the wrong question - any "bloat" in your example has nothing to do with templates. (the answer to your question, btw, is to take the address of the member function in both modules and you'll see they're the same)

想要问的是,对于每个模板实例化,生成的可执行文件线性增长?

What you really want to ask is, for each template instantiation, does the resulting executable grow linearly? The answer is no, the linker/optimizer will do magic.

编译一个exe,创建一个类型:

Compile an exe that creates one type:

Array< int, 100 > MyArray;

注意生成的exe大小。现在再做一次:

Note the resulting exe size. Now do it again:

Array< int, 100 > MyArray;
Array< int, 99 > MyArray;

等等,30个左右的不同版本,绘制结果exe大小。如果模板和人们认为的一样可怕,每个唯一的模板实例化的exe大小将增加一个固定的金额。

And so on, for 30 or so different versions, charting the resulting exe sizes. If templates were as horrible as people think, the exe size would grow by a fixed amount for each unique template instantiation.

这篇关于C ++模板:说服自己对代码膨胀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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