In the following example, type inference fails for the call to mkPair2
:
#include <functional>
template <class A, class B>
struct Pair {
A left; B right;
};
template <class A, class B>
Pair<A,B> mkPair1 (A left, B right) {
return (Pair<A,B>) { left, right };
}
template <class A, class B>
std::function<Pair<A,B>(B)> mkPair2 (A left) {
return [left] (B right) {
return (Pair<A,B>) { left, right };
};
}
Pair<int, char> ex1 = mkPair1 (2, 'a');
Pair<int, char> ex2 = mkPair2 (2) ('a');
The problem is that mkPair2
has two template arguments, but the call (2)
only provides it with one of them, so the compiler immediately throws its hands up and decides that the program is ambiguous, even though the second type can be inferred from the following ('a')
call.
This can be resolved by giving the compiler the types manually mkPair2<int,char> (2) ('a')
, but having to hold the compilers hand like that gets old really quickly.
Is there any way to trick the compiler into continuing type checking, provided that every type will eventually be resolved?