Aug 16, 2011 at 6:29pm UTC
Hi ,
Given the following code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
using namespace std;
template <class T>
void print (T obj1 = 0 , T obj2 = 0)
{
cout << obj1 + obj2 << endl;
}
int main() {
print();
return 0;
}
I do not understand why the line "print();" won't compile , but the line
"print(3);" does.
Can you please explain ?
10x,Dave
Last edited on Aug 16, 2011 at 6:29pm UTC
Aug 16, 2011 at 6:53pm UTC
That is a template function. You need to pass a parameter for the compiler to know how to instantiate it, or you could explicitly pass the template parameter:
Last edited on Aug 16, 2011 at 6:54pm UTC
Aug 16, 2011 at 6:54pm UTC
if you just say print(), then the compiler doesn't know what type you want for T.
If you say print(3), then the compiler can tell that you want T to be int, and therefore it can call the function.
Another way to say which type you want is to say so explicitly:
print<int >();
Aug 16, 2011 at 6:57pm UTC
But the template has default values of zero and zero , ain't that enough ?
10x
Aug 16, 2011 at 7:01pm UTC
Last edited on Aug 16, 2011 at 7:01pm UTC