templates and memory occupancy

Dear all,

Let us consider the following two classes:

1
2
3
4
5
6
7
8
9
10
11
12
13
class case1
{
  public:
  int n;
  float x;
};

template<int n>
class case2
{
  public:
  float x;
};


Now, let's suppose that I instantiate an array of 100 elements of each class:

1
2
case1 c1[100];
case2<20> c2[100];


My question is this: will c2 occupy roughly half of the memory than c1?
will the value c1.n be allocated 100 times, while the value c1.n wil be allocated only once?


Thank you all.
Panecasareccio.
> My question is this: will c2 occupy roughly half of the memory than c1?

Check it out:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

class case1
{
  public:
      int n;
      float x;
};

template<int n>
class case2
{
  public:
      float x;
};

int main()
{
    case1 c1[100];
    case2<20> c2[100];

    std::cout << "case1: " << sizeof(c1) << '\n'
              << "case2: " << sizeof(c2) << '\n' ;
}
Thanks!!!

By the way, where is the value case2::n stored?
> where is the value case2::n stored?

There is type with the name case2, case2<20> is a type, case2<25> in another type, and so on.
There is no object with the name case2::n or case2<20>::n

The n in template<int n> is a prvalue (pure rvalue); it is a constant known at compile time; it need not be stored anywhere. It can be used like an integer literal:

1
2
3
4
5
6
7
int i = 23 ; // fine; i is initialized with the prvalue 23, 
             // but the 23 itself need  not be stored anywhere

// int* p = std::addressof(23) ; // *** error, 23 is an rvalue

int j = std::strlen("abcd") ; // fine:  j is initialized with the prvalue returned by strlen.
char cstr[23] ; // fine 



Topic archived. No new replies allowed.