2

I'm trying to learn templates in c++ and i came across with a doubt that i can't find answers for. I'm sorry in advance if this is not a proper question.

If i have the following code:

template< class T >
T func( T a, T b )
{
    return a + b;
}

And then:

int number = func( 2, 3 );

Will number simply be set to 5 or will a function

int func( int a, int b )
{
    return a + b;
}

be generated?

I need to know if i can make a template that checks if a certain string is in a file.

BisaZ
  • 221
  • 1
  • 2
  • 9

2 Answers2

6

Both (: The code:

int number = func( 2, 3 );

will instantiate the template function for int type, but compiler may (depending on compiler options) actually optimize it to just:

int number = 5;
JarkkoL
  • 1,898
  • 11
  • 17
  • Thank's a lot for your answer i needed to know what exacly i could do with templates. I found that giving use to templates is harder than actualy learning them... – BisaZ Jun 14 '14 at 22:02
  • 1
    Once you start to write same code but for different types, that's a good candidate to convert your code to a template. – JarkkoL Jun 14 '14 at 22:09
  • @BisaZ would you like to mark this question as "correct"? :) That will let people know that this has been resolved. – Drew Dormann Jun 14 '14 at 23:22
  • Done sorry i did not do it earlier. – BisaZ Jun 15 '14 at 09:29
1

A function equivalent to

int func( int a, int b )
{
    return a + b;
}

will certainly be generated (unless, of course, it's optimized out). To see this, try

int (*func_int)(int, int) = func<int>; // pointer to instantiated function
int number = func_int(2, 3); // sets number to 5
Brian Bi
  • 111,498
  • 10
  • 176
  • 312