Reputation: 115
I have function template:
template<class Ty,
typename std::enable_if< std::is_arithmetic<Ty>::value >::type* = nullptr >
inline void printBars(std::vector<Ty> const& y,
std::function<Ty(Ty)> const& alt);
I wonder if there is some approach to use the type deduced from first function argument in the second argument in order to make possible to use this function template in such way:
#include <cmath>
printBars(y, log10);
Is there?
Upvotes: 1
Views: 130
Reputation: 145239
Any computer science problem can be solved by another level of indirection.
In the public function just let the second argument be of type U
, a second template parameter, and forward the call to the real function implementation.
This approach is also necessary if, for example, you want to differentiate between array and pointer argument.
Example.
namespace detail{
template< class T >
void printBars( std::vector<T> const& y, std::function<T(T)> const& alt)
{
// whatever.
};
} // namespace detail
template<
class T, class U,
class enabled = std::enable_if< std::is_arithmetic<T>::value >::type >
void printBars( std::vector<T> const& y, U const& alt )
{
detail::printBars_impl<T>( y, alt );
};
Disclaimer: code not touched by compilar's hands, + just out bed (no coffee yet). ;-)
Thinking about it, the best here is probably to do as Xeo suggests and entirely dispense with the std::function
, for it seem to just impose an unreasonable constraint on the caller; instead just check whether the argument supports what you want to use it for.
Upvotes: 1