Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unambiguously refer to function with template overloads

Tags:

c++

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?

like image 605
toth Avatar asked Jul 08 '14 15:07

toth


1 Answers

use template specialization:

template<>
int f<int>(int x ) { return 1; } // a)
like image 113
spin_eight Avatar answered Nov 02 '22 06:11

spin_eight