Question

As some of you may know from my recent posts i am studying for a C++ exam which the content for the class was delivered very poorly. I am basically having to self teach everything myself so bear with me here.

This is an exam question:

(i)Explain the concepts of templates as defined in the C++ language. Be sure to differentiate between what the programmer does and what the compiler does.

My current rationale:

(i) A template allows a function or class to operate using generics. This allows the programmer to effective program X functionality once, and be able to use this functionality with many different data types without having to rewrite the application or parts of the application multiple times.

My problem is i have no idea how the compiler handles the use of templates.

I am unsure what the compiler does at this stage, if somebody could clear this up it would be helpful.

Was it helpful?

Solution 2

let's say you write a function using templates:

template <typename T>
void function(T t){
 doSomething();
}

for each data type you call this function, the compiler simply replaces the 'T' with that data type, say 'int' and generates code for that like you've written this function with 'int' instead of 'T' since the beginning. This is probably the right (but not the complete) answer if others agreed.

OTHER TIPS

Templates in C++ are implemented through substitution. It's not like Java generics which just type check the code which involves the generics class and then compiles it using raw references (type erasure).

Basically C++ creates a different class/method for each actual template argument used in your code. If you have your

template<typename T>
void myMethod(T t)
{
  //
}

what happens at compile time is that a different method is compiled for each type the template is actually used. If you use it on myMethod(50) and myMethod("foo") then two overloaded version of the method will be available at runtime. Intuitively this means that templates could generate code bloating but in practice the same expressiveness is obtained by a larger codebase without templates with less readability so that's not a real concern.

So there is no black magic behind them (ok there is if you consider meta programming or partial specialization).

For each instance of an object of a different type that you create or in case of functions the different type of arguments that you use, the compiler simply makes an overloaded version at compile time. So if you have a template function like a sort function and use that function for int and double arrays, then the compiler have actually made two functions: one using int and the other using double. This is the simplest explanation I could give. Hope it's useful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top