Function return type template parameters cannot be deduced

I have this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;

template <typename T, typename U> map<T, T> func1( U u ) {
	T t = u[0];
	map<T, T> m;
	m[t] = t;
	return m;
}

int main() {
	vector<int> vect;
	vect.push_back(1);
	map<int, int> m = func1(vect);
	return 0;
}


and it does not compile. The error is:

test.cpp: In function ‘int main()’:
test.cpp:20:30: error: no matching function for call to ‘func1(std::vector<int>&)’
test.cpp:20:30: note: candidate is:
test.cpp:8:45: note: template<class T, class U> std::map<T, T> func1(U)
test.cpp:8:45: note: template argument deduction/substitution failed:
test.cpp:20:30: note: couldn't deduce template parameter ‘T’

Can someone explain what is the problem, please ?
"test.cpp:20:30: note: candidate is:"
"test.cpp:8:45: note: template<class T, class U> std::map<T, T> func1(U)"
"test.cpp:8:45: note: template argument deduction/substitution failed:"

Your compiler already gave u a good clue.

when calling function "func1" you have to tell it what Datatype your T and U are supposed to be:

1
2
map<int, int> m = func1<int, vector<int>>(vect); 
//we now called func1 with T as int and U as vector<int> 
Last edited on
> map<int, int> m = func1(vect);
There is no way for `func1()' to know that T=int

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <typename U> 
std::map<
	typename U::value_type, //dependant name
	typename U::value_type
>
func1( U u ) {
	typename U::value_type t = u[0];
	std::map<
		typename U::value_type,
		typename U::value_type
	> m;
	m[t] = t;
	return m;
}
Many thanks from C++ newbie :)
Topic archived. No new replies allowed.