So I want to pass mathematical functors to std::function
s.
std::function< double( double ) > squareRoot( std::sqrt );
I get an error saying it could not resolve the overload on MSVC and GCC. However this works
std::function< double( double ) > squareRoot( ( double( * )( double ) ) std::sqrt );
std::cout << squareRoot( 4.0 ) << "\n";
Scarily it works if we pass the address of the functor
std::function< double( double ) > squareRoot( ( double( * )( double ) ) &std::sqrt );
std::cout << squareRoot( 4.0 ) << "\n";
Both of the latter (trivial) programs produce valid output.
What is the proper way to specify the particular overload of a functor when passing it to something like std::function
(bonus if can someone explain the template parameter syntax especially in relation to this)?
UPDATE 0
The following works under GCC but not MSVC, so I am updating the title to include functions.
std::function< double( double ) > squareRoot( sqrt );
UPDATE 1
The previous example works under both GCC and MSVC include just <cmath>
but not when <math.h>
is included after. Im not sure if I am actually dealing with a function or a functor.
The way you've done it (casting std::sqrt
to the specific function pointer type required) is the correct way to pick out the specific overload you want. As you observed, it works both with and without the explicit &
. It would be considered better style to use static_cast<double(*)(double)>
than the C-style cast, in order to avoid accidentally performing a reinterpret_cast
.
There is no special template parameter syntax here to be aware of. std::sqrt
is not a template, so trying to specify template parameters (like std::sqrt<double>
) would not be correct. You also can't explicitly specify the template arguments for the std::function
constructor (this is a syntactic issue in C++: there is no constructor name to put the template arguments after).