2

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

de.
  • 7,068
  • 3
  • 40
  • 69
  • You can use a string_view if you like. – Marc Glisse Jul 20 '21 at 15:25
  • Please don't post images of text, thanks. Function template instantiations usually cause binary code to be generated. This may result in increased binary sized. This was the case wince the introduction of templates to C++ many moons ago, and will likely continue to be the case for the foreseeable future. As for efficiency, you need to measure how efficient it is in your specific case. (But do not measure binaries produced without compiler optimisations) – n. m. could be an AI Jul 20 '21 at 15:27

1 Answers1

3

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 :)

paulsm4
  • 114,292
  • 17
  • 138
  • 190