Ashish Kapoor Ashish Kapoor - 5 months ago 17
C++ Question

Memory Efficient: Templates vs Basic data types

Is the use of templates better than basic data types in terms of memory allocation and management?

N O N O
Answer Source

Just in short:

templates - a way to write code once in a generic way, and in compilation time the compiler will generate code according to the template, if you used the templatic code.

example:

  #include <iostream>


template<typename T>
T MultiplyByFive(T _val)
{
    return _val * 5;
}

int main()
{
    std::cout << MultiplyByFive(5) << " " << MultiplyByFive(5.5) << std::endl;
    return 0;
}

In this example, the compiler will generate two MultiplyByFive functions. One for integer and one for double. The output will therefore be:

25 27.5

That's because these functions have been called. Now we have two function in the code (generated by the compiler)

int MultiplyByFive(int _val)
{
    return _val * 5;
}


double MultiplyByFive(double _val)
{
    return _val * 5;
}

We didn't code them directly, but the compiler did according to our template.

Memory allocation has little to do with template. Dynamic memory allocation is determined in run time (in c++ by the new operator). Static and local variable are determined in compile time, but it has nothing to do with generating code.

If I didn't understand the question, you're more then welcome to clarify.