C++ templates
-
Hi, I have found out (the hard way!) that you can't have a .cpp file with your function definitions if you are using a template class. All your function definitions must be in the .h file. Why is this? Thanks for any info.
You can put the code in a C++ file, you just need to change how you define your templates. I would not recommend that though, justuse a header file it's much easier. regards,
Jonathan Wilkes Darka[Xanya.net]
-
You can put the code in a C++ file, you just need to change how you define your templates. I would not recommend that though, justuse a header file it's much easier. regards,
Jonathan Wilkes Darka[Xanya.net]
-
Hi, Thanks for that, but do you know why the C++ compilier objects to having function definitions in the .cpp ? Thanks.
AFAIK it is because template code is generated by your compiler. It means that when you have a template instantiation (something like list<float> ) your compiler will generate code corresponding to this template type. To be able to generate the code, it needs the complete function implementation.
Cédric Moonen Software developer
Charting control [v1.2] -
Hi, I have found out (the hard way!) that you can't have a .cpp file with your function definitions if you are using a template class. All your function definitions must be in the .h file. Why is this? Thanks for any info.
Yes, all in the .h file. Only specializations must be putted in the .cpp file (declaraion, of course, in the .h file).
minkowski wrote:
Why is this?
I think that this has only a reason related to how the compiler works to elaborates the templates. I hope that this isn't a problem for you.:~
Russell
-
Hi, Thanks for that, but do you know why the C++ compilier objects to having function definitions in the .cpp ? Thanks.
You do *not* have to have definitions in th ecpp. You do this to (partially) separate interface and implementation. With templates, every instantiation (for type A, type B etc) creates a new, distinct type: vector<A> is different from vector<B>. And for this instantiation, the compiler needs the complete definition of the template. Therefore it is easiest to put the template in the header, to have it ready when you need it.
Though I speak with the tongues of men and of angels, and have not money, I am become as a sounding brass, or a tinkling cymbal.
George Orwell, "Keep the Aspidistra Flying", Opening words -
Hi, I have found out (the hard way!) that you can't have a .cpp file with your function definitions if you are using a template class. All your function definitions must be in the .h file. Why is this? Thanks for any info.