1
#include<iostream>
using namespace std;
template<class T>
void f(T &i)
{
    cout<<"1";
}
void f(const int&i)
{
    cout<<"2";
}
int main()
{
    f(7);
}

I have used a template function and a normal function. But the function with const int argument is executing when called. Why is that so?

coderag
  • 13
  • 2
  • 4
    The function template doesn't come into play because 7 cannot bind to a non-const reference. – n. m. could be an AI Jun 06 '18 at 04:44
  • 1
    Also relevant, because even if the signature was `void f(T i)` and `void f(const int& i)`, the output would still be `2`: https://stackoverflow.com/questions/14666219/why-does-overload-of-template-and-non-template-function-with-the-same-signature – Tas Jun 06 '18 at 04:59
  • What if i give const T&i – coderag Jun 06 '18 at 05:02
  • Because 7 is a literal, so a constant? – Jean-Baptiste Yunès Jun 06 '18 at 05:07
  • RE: *"What if i give const T&i "* - SO is not a tutoring site. And besides, learning C++ via SO isn't a good way to go about it. Your questions indicate you haven't gotten through the basics of it yet. I suggest you browse our [community curated book list](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa), and pick a good beginner book from it. – StoryTeller - Unslander Monica Jun 06 '18 at 05:11
  • 1
    Possible duplicate of [Why does overload of template and non-template function with the "same signature" call the non-template function?](https://stackoverflow.com/questions/14666219/why-does-overload-of-template-and-non-template-function-with-the-same-signature) – acraig5075 Jun 06 '18 at 05:56

1 Answers1

0

When your code is compiling, depend on type of arguments and number of argument, compiler will find the most related function to response your function call f(7) before move to Template functions. In this case, the most related function is void f(const int&i) so you got 2 as an output.

TaQuangTu
  • 2,155
  • 2
  • 16
  • 30