开发者

Template argument deduction error

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

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

Why does foo(5)开发者_如何学JAVA fail but foo< int >(5) work?


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


The compiler does not know what is T.


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.


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!!
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜