Passing a class as a type in a template class

I am trying to pass a class as a type to a template class. This class's constructor needs an argument but I cannot find the correct syntax. Is it possible?

Here is an example of what I described above. I did not compiled it, it is for illustrative purpose only. And of course argument val of the myData constructor would be doing something more useful than simply initializing an int....

template <class T>
class templateClass {
templateClass() {};
T data;
};

class myData {
myData(int val): size(val) {};

int size;
};



main () {

templateClass dummy(4);

}

My real code would only compile is I add the myData constructor:

myData () {};

and gdb confirmed that it is this constructor that get called, even with dummy(4).

I just spend a full afternoon googling about this topic but without success.... :-(
You forgot to make the constructor public and you never made a constructor for templateClass that takes a variable type T as argument. Finally you need angle brackets to properly instantiate a templated class:

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
template <class T>
class templateClass {
T data;

public:
	templateClass() {};
	templateClass(T data) : data(data) {}
};

class myData {
int size;

public:
	myData(int val): size(val) {};
};



int main () {

	templateClass<int> dummy(4);
	myData dummy2(4);
	
	return 0;
}
oups, I realize that I forgot to specify the type when I instantiated the class; it should be:

templateClass<myData> dummy (4);

in order word, I am using a class as the type for the template class and need to pass an argument to this class's constructor. (not the template class but the other class used as a type).
Then do this:

1
2
3
4
5
6
7
int main () {

        myData dummy2(4);
	templateClass<myData> dummy(dummy2);
	
	return 0;
}


Or

1
2
3
4
5
6
int main () {

	templateClass<myData> dummy(myData(4));
	
	return 0;
}
Last edited on
Ok, this is not exactly what I was expecting; I was hoping to pass argument(s) to the constructor of object(s) of type T in templateClass.

What you are proposing is to creates an object of type myData and pass it as an argument to the constructor of templateClass. I guess I just have to a have copy constructor in myData and use it initialize local object(s) in templateClass. It is not exactly the same thing but could achieve the same effect, unless I do not pay attention and the object passed to the templateClass's constructor is modified after being initialized and before initializing an object of type templateClass<myData>
Topic archived. No new replies allowed.