Vector with tenplates

hey guys,

regarding templates and vectors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

template <class T>
class cls{

  public:
  vector<T> vec(200,NULL); // error
  
  cls(){}


};

template <class T>
class cls2{

  public:
  vector<T> vec = vector<T>(200,NULL); // valid
  
  cls2(){}


};



what is the difference by declaring and initialising a vector in cls isn't this not the same as in cls2? in cls I get an error but in cls2 this is valid


Thanks
Last edited on
Don't put NULL as the second parameter. How do you know that NULL (basically just 0) is appropriate for initializing any T? Just leave the second parameter out and T will be initialized with the appropriate initializer. (In C++ we don't use NULL, anyway. Pre-C++11 we use 0; since then we use the keyword nullptr.)

As for your question, obviously the two aren't exactly the same. Only the second is allowed, although I don't know exactly why (since, although they aren't the same, they do seem essentially equivalent). Before the second version was allowed, we just used the ctor.

Note that a "complete" program is useful so people can easily run it by pressing the little gear symbol.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <vector>
using namespace std;

template <class T> class cls1 {
public:
//    vector<T> vec(200); // error
};

template <class T> class cls2 {
public:
    vector<T> vec = vector<T>(200); // valid
};

template <class T> class cls3 {
public:
    vector<T> vec;
    cls3() : vec(200) {}  // using ctor
};

template <class T> class cls4 {
public:
    vector<T> vec{1, 2, 3, 4, 5}; // init with list
};

int main() {
    cls1<int> c1;
    cls2<int> c2;
    cls3<int> c3;
    cls4<int> c4;
}

Last edited on
Note that a "complete" program is useful so people can easily run it by pressing the little gear symbol.

True, but be careful with templates, you could still have "compile" errors when you actually try to use one of those classes.

Note that first class should be acceptable if you used uniform initialization.

1
2
3
4
template <class T> class cls5 {
public:
    vector<T> vec{200}; 
};
Good point. I should've instantiated the templates in main. I now added that in.

But vec{200} only creates a vector of one element with the value 200. So it's not the same thing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
using namespace std;

template <class T> class cls2 {
public:
    vector<T> vec = vector<T>(200);
};

template <class T> class cls5 {
public:
    vector<T> vec{200};
};

int main() {
    cls2<int> c2;
    cls5<int> c5;
    cout << "c2: " << c2.vec.size() << ": " << c2.vec[0] << '\n';
    cout << "c5: " << c5.vec.size() << ": " << c5.vec[0] << '\n';
}

Output:
c2: 200: 0
c5: 1: 200

Last edited on
Topic archived. No new replies allowed.