C ++模板中的代码重用(或不重用)

时间:2015-10-19 10:49:35

标签: c++ templates

在我直到现在阅读的所有书中,他们都说C ++模板为我们使用的每种类型生成一个代码实例。

另一方面,书中说在C#中代码被重用了。

所以我在很多书中搜索过,我在一本非常古老的书中找到了以下C#的例子。

1)价值类型

List<int> intList1  = new List<int>();
List<int> intList2  = new List<int>();
List<bool> boolList = new List<bool>();

在这种情况下(值类型),编译器为intList1和intList2(相同类型)生成一个代码实例,并为boolList生成一个代码实例。

2)参考类型

List<Dog> dogList1 = new List<Dog>();
List<Dog> dogList2 = new List<Dog>();
List<Cat> catList  = new List<Cat>();

在这种情况下(引用类型),编译器只为DogList1,dogList1和catList生成JUST ONLY代码实例,因为只要它可以表示指向对象的指针,所有引用类型都可以共享一个实现。

这对我来说非常清楚(作为一个C ++开发者),但我对c ++模板的同样事情很有说服力。

在创建C#之前很久,C ++也有值类型和引用类型。

因此,让我们重写C ++中的avove示例

1)价值类型

vector<int> intList1;
vector<int> intList2;
vector<bool> boolList;

在这种情况下,我毫不怀疑intList1和intList2共享相同的代码,boolList需要另一个实现

2)参考类型

vector<Dog *> dogList1;
vector<Dog *> dogList2;
vector<Cat *> catList;

我的问题是:

我可以得出结论,在第二种情况下(指针的向量),只要所有向量指针(向量&lt; Dog *&gt;和向量&lt; Cat *&gt;)和所有指针都是相同的,它们都共享相同的模板实例化。相同的大小(32位或64位,具体取决于平台)?

2 个答案:

答案 0 :(得分:4)

(你的问题中有一些混乱,但让我跳过这个并解决实际问题。)

不,你不能这么认为。

这主要是因为无论你的系统是32位还是64位,指针都不必必须大小相同。

答案 1 :(得分:1)

可能你可以使用静态变量来检查这个,如下所示:

#include <iostream>
using namespace std;

template <typename T>
class Wrapper
{
public:
    static int count;
    T d_wrapped;

    Wrapper(T i_wrap) : d_wrapped(i_wrap)
    {
        ++count;
    }
};

template <typename T>
int Wrapper<T>::count = 0;

int main() {
    Wrapper<int> wi(1);
    Wrapper<int> wi2(2);
    Wrapper<float> wf(1.0f);

    Wrapper<int*> wip(new int());
    Wrapper<float*> wfp(new float());

    cout << Wrapper<int>::count << ' ' << Wrapper<float>::count << '\n' <<
            Wrapper<int*>::count << ' ' << Wrapper<float*>::count << '\n';
    return 0;
}

Ideone live code

在ideone上启动表明,即使是指针,我们也有不同的静态变量。

相关问题