Template argument output error

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) works?

+3
source share
5 answers

You might want to write

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

Update

Below is the full 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 conclusion:

void foo(T) [with T = int] called with 5
void foo(T) [with T = int] called with 7
+4
source

The compiler does not know what T. is.

+3
source

, , ( )

, , T.

0

foo (5) , foo <int> (5) ?

, T [ foo(5)].

You can leave the template arguments at the end, and not at the beginning or in the middle:

For instance:

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

Usually you have something like this:

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

Then, when you pass intas a parameter, the compiler can infer what it Tshould be int. Since your code does not use Tanywhere, the compiler has nothing to do with what could be.

0
source

Source: https://habr.com/ru/post/1767674/


All Articles