Grandissimo
Grandissimo

Reputation: 31

Template instantiation causing function bloating

As i started experimenting more in depth with C++1x features i ran into some thinking. For example when there is this construct template<unsigned int N> unsigned int functionForTest(const char (&a)[N]); and the usage of it like

functionForTest("Hello"); ---> const char [6]

functionForTest("Hello World") ---> const char [12];

then c++ ends up instantiating 2 functions with 2 different parameter types and that means increase in binary size if this function is used with different sizes. How efficient is that? Is it compiler specific? Isn't the traditional C-like array and size passing to function much more efficient here?

This is how i build g++ -std=c++17 -Xlinker -Map=output.map compilerDiffs.cpp -o test.exe and thats a sample of the map file inspected to come to this conclusion

samples of Map file

Upvotes: 2

Views: 229

Answers (1)

paulsm4
paulsm4

Reputation: 121869

Generics ("templates" in C++) are a HUGE win for any type-safe language:

https://www.geeksforgeeks.org/generics-in-c/

The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter.

The advantages of Generic Programming are

  • Code Reusability
  • Avoid Function Overloading
  • Once written it can be used for multiple times and cases.

And yes - that means if you instantiate a template for two different types ... then your compiler will generate two different functions. That's not an "inefficiency" - that's the whole POINT. You've written one, "generic" function; the compiler takes care of the rest.

You no longer have to "re-write" the same function over and over again for each specific type.

That's a "win".

The problem above is that "templates" are simply the wrong choice for your particular example. You'd probably want a "std::string" instead (in which case there's no need for "N". Alternatively, maybe you'd want to pass "N" as a function parameter.

Templates are Good. But you need to use the right tool for the right job :)

Upvotes: 2

Related Questions