tags:

views:

74

answers:

5
template <typename T>
void foo(int i)
{
  //nothing inside
}

int main()
{
   foo(5); //fails
   foo<int>(5); //works
}

Why does foo(5) fail but foo< int >(5) work?

+3  A: 

The compiler does not know what is T.

Benoit
A: 

If you define a function as a template function, then you need to define what type you are going to use (even though your function does not use the template type)

So you need to tell the compiler what type T is.

Ólafur Waage
+4  A: 

You perhaps wanted to write

template <typename T>
void foo(T i)          // note the type of i
{
  //nothing inside
}

Update

Following is complete code

#include <iostream>
using std::cout;

template <typename T>
void foo( T i ) {
    cout << __PRETTY_FUNCTION__ << " called with " << i << "\n";
}

int main() {
    foo( 5 );
    foo<int>( 7 );
}

and output:

void foo(T) [with T = int] called with 5
void foo(T) [with T = int] called with 7
ArunSaha
+2  A: 

Why does foo(5) fail but foo< int >(5) work?

Because there is no way for the compiler to determine what T is [from foo(5)] .

You can only leave template arguments of the end, not the beginning or middle:

For example:

template<typename T, typename U> 
void foo(T t) 
{
}
template<typename T, typename U> 
void bar(U u) 
{
}

int main() 
{
    foo<int>(5);      // Error!! Compiler cannot decide what `U` is
    foo<int, int>(5); // Works!!

    bar<int>(5);      // Works!! `U` deduced from `5` (int)
    bar<int, int>(5); // Works!!
}
Prasoon Saurav
A: 

Normally you'd have something like this:

template <class T>
void foo(T i) { }

Then, when you pass an int as the parameter, the compiler can deduce that T must be int. Since your code doesn't use T anywhere, the compiler has nothing to go on to deduce what it might be.

Jerry Coffin