Search code examples
c++templatesgenericsfunction-templatesexplicit-specialization

Function Templates - Explicit specialisation vs Global Functions (C++)


I know that Function Templates are used so as to make the functions portable and so that they could be used with any data types.

Also Explicit Specialization of templates is done if we have a more efficient implementation for a specific data type.

But then instead of Explicit Specialization we could also just code a Nontemplate Function which could be called from main . This would save us some processing time as the compiler would locate Nontemplate Functions faster than Explicitly Specialized Templated Functions which would in turn be better in terms of efficiency.

So why do we use Explicit Specialization when we have the alternative of just calling Nontemplate Functions?

Please correct me If I'm wrong!

Edit 1: I was told by my professor that whenever we make function templates and call the function from main ,the compiler first looks for a templated function and if its not able to locate that,then it searches for a function template from which it in turn makes a templated function and then calls for it.


Solution

  • It sounds like you're confusing compile-time efficiency with run-time efficiency. The choice of which function to call is made at compile time, not run time, so it will make no difference to the run time of the program.

    Explicit Specialization is used when you have a special case that can benefit from special treatment. Sometimes this backfires, as in the case of std::vector<bool>, while other times it's quite handy. It means that the user of the function doesn't need to be aware that there's a special case; it's just transparent.