Click here to Skip to main content
15,891,976 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

If I compile the following program, it compiles successfully.
As well as it runs very well. Once I run it there is no output.

Anyone please explain
1) How this program compiles ?
2) How does template work in this case ?

template <int iValue>
void Add(int mValue)
{
    printf("I am in Add");
}

int _tmain(int argc, _TCHAR* argv[])
{
      Add<"sss">;
      return 0;
}


Thanks in advance.
Posted

The line...:

C++
Add<"sss">;


doesn't actually cause any code to be generated. There's no function call, no object definition. You're not telling the compiler to do anything. If you try actually doing something with your function:

Add<"sss">( 128 );


then your compiler's going to throw a fit and not build the program.

Cheers,

Ash
 
Share this answer
 
Comments
san123pune 27-Jul-10 8:28am    
But how compiler handles this internally ?
Why compiler accept "sss" instead of int?
Aescleal 27-Jul-10 11:12am    
It doesn't accept it. Templates expansion errors only occur when they're first used. You're not using the template, you're just making a half-arsed expansion.

As I said most compilers will give you a warning if you do what you have. If yours doesn't then it might be an idea to change it.

Ash

PS: Look up SFINAE (Substituion Failiure Is Not An Error) online. It'll point you to the section of the C++ standard that describes how templates are expanded.

PPS: Edited to make the language more precise and use the same terms as the standard
if I do
void func(int x)
{ cout << "in func" << endl; }

int main()
{
   func;
   return 0;
}

No outoput will be produced, since func is not a function call.
Now, in I do
C++
template<int N>
void func(int x)
{ cout << "in func" << endl; }

int main()
{
   func<"hhh">;
   return 0;
}

The compiler will even NOT produce the code for "func", since code is produce at the time it is required to be used.

If I do
C++
int main()
{
   func<"hhh">(128);
   return 0;
}


The compiler attempt to generate func<"hhh">(int) and have no way to do, hence will generate an error.
If I do
C++
int main()
{
    func<10>(100);
    return 0;
}


The compiler generates func<10>(int) and calls it passing 100 as a parameter.

Now, you understand all this correctly, it should be clear to you that
func<10> and func<15> are two different and distinct functions.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900