Code reuse (or not) in C ++ templates

In all the books that I read so far, they said that C ++ templates generate one copy of the code for each type we use.

On the other hand, the books say that in C # the code is reused.

So, I did a search in many books, and I found in one very old book the following examples for C #.

1) Value types

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

In this case (value types), the compiler generates ONE code instance for both intList1 and intList2 (the same type) and ONE code instance for boolList.

2) Link types

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

In this case (link types), the compiler generates ONLY ONLY one code instance for dogList1, dogList1 and catList, because since it can represent a pointer to an object, all reference types can share the same implementation.

( ++-), , ++-.

# ++ .

avove ++

1)

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

, intList1 intList2 , boolList

2)

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

:

, ( ) , ( <Dog> <Cat> ), (32 64 )?

+4
2

( , ).

, .

, , , 32 64 .

+4

, , , :

#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 , .

+1

Source: https://habr.com/ru/post/1612230/


All Articles