2

I had created a Template Specialized function and a non template function with the same arguments. Since effectively both are same functions, I was not sure how C++ compiler would run it as now it has two same functions, one is a template specialized the other is a non template one. I was expecting this would result in a compiler error as compiler would find two functions with the same parameters and return type (In this case void foo(string) ). But looks like the non template version is the one that executes when this is called. So is there a precedence when this is done?

Kindly let me know if I have misunderstood.

Code: This prints 'String Non-Template'

#include <iostream>
#include <string>
using namespace std;

template<typename T>
void foo(T input)
{
    cout <<"Generic Template"<<endl;    
}

template<>
void foo<string>(string input)
{
    cout <<"String Template"<<endl;
}

void foo(string input)
{
    cout <<"String Non-Template"<<endl;
}

int main() {

    string input = "abc";
    foo(input);

    return 0;
}
Invinsible
  • 21
  • 1

1 Answers1

4

A regular function is always preferred over a function template, even a specialization of the function template.

From the C++ Standard:

13.3.3 Best viable function [over.match.best]

1 Define ICSi(F) as follows:

...

Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then

...

-- F1 is a non-template function and F2 is a function template specialization, or, if not that,

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270