Reputation: 131
I am learning how to use templates in conjunction with function overloading, but I can't seem to grasp it; specifically, I have 2 functions with the same name, one accepts 2 int parameters, the other 3 int parameters. I need them to return, respectively, a double/triple pointer to a type which should be defined by the function caller; in other words:
template <typename T>
T** Foo(int p0, int p1){
T** ret = nullptr;
// ... do stuff with ret ...
return ret;
}
template <typename T>
T*** Foo(int p0, int p1, int p2){
T*** ret = nullptr;
// ... do stuff with ret ...
return ret;
}
int _tmain(int argc, _TCHAR* argv[])
{
double** d2 = Foo(1, 2);
double*** d3 = Foo(1, 2, 3);
int** i2 = Foo(1, 2);
int** i3 = Foo(1, 2, 3);
}
I was expecting d2 and i2 to be returned by the first Foo(), d3 and i3 by the second; instead I get Errors C2780 and C2783 from each one of the calls in main(). What am I missing?
Upvotes: 0
Views: 84
Reputation: 10326
The compiler cannot automatically deduce the template parameter (because it is only dependant on the return type and not any of the arguments). You should use this code instead:
double** d2 = Foo<double>(1, 2);
double*** d3 = Foo<double>(1, 2, 3);
int** i2 = Foo<int>(1, 2);
int*** i3 = Foo<int>(1, 2, 3);
(Note I also made a correction on the final line: you had int**
instead of int***
)
Upvotes: 5