Suppose I have the following definitions:
int f(int ) { return 1; } // a)
template<typename T> int f(T x) { return 2; } // b)
I understand that if I call f
, e.g. f(1)
, the non-template overload a) will be preferred, but is there a way to unambiguously refer to a)? For instance, I can use f<int>
to refer to b) unambiguously.
As an example of why this would be useful, consider the following function:
template<typename Func, typename T> void print_result(Func f, T arg)
{
std::cout << f(arg) << std::endl;
}
If I try to use it on f
, e.g, print_result(f,1)
, I get a compilation error (the compiler does not know which f
I mean). I can use print_result(f<int>,1)
to tell it to use b), but how do I tell it to use a) ?
I found I can use print_result(static_cast<int (*)(int)>(f), 1)
, but this feels hacky and is cumbersome. Is there a better way?
use template specialization:
template<>
int f<int>(int x ) { return 1; } // a)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With