I have the following C++ code which compiles:
A function:
template <typename T> T funcC(int a, double b)
{
return a + b;
}
Then in main, I do the following:
int (*anythingInt)(int,double);
double (*anythingDouble)(int,double);
anythingInt = &funcC;
anythingDouble = &funcC;
std::cout << anythingInt(12, 17.5) << std::endl;
std::cout << anythingDouble(12, 17.5) << std::endl;
As I expected, the first cout gives 29, the second one gives 29.5. My question is - how does this work?
Does the compiler know to instantiate funcC with a double return type because anythingDouble uses this return type? If I do anythingInt = &funcC<int>
and anythingDouble = &funcC<double>
, then it yields the same behavior.
From what I read, function pointers can point to instances of template functions, not template functions themselves - like here.
I am not doing anything of it, so how does it work, and is it legitimate code?