How to keep signature of a callable argument visible in a C++ template? -
the function f()
below takes callable argument fc
signature nicely visible in function definition.
// scaffolding function definition template<typename t> struct identity { using type = t; }; // still scaffolding function definition template<typename t> using make_deducible = typename identity<t>::type; // function definiton template <typename t> t f(t val, make_deducible<std::function<t(t)>> fc) // see fc's expected signature { return fc(val); }
note can called in following ways:
int g(int i) { return * i; }; f(5, g); // call function ptr: used std::function<int(int)> fo{[](int i){ return * i; }}; f(6, fo); // call std::function object: tedious f(7, [](int i){ return * i; }); // call lambda closure: usual use case
what bothers me definition of f()
requires scaffolding work. so, questions is:
is there less roundabout way of doing while keeping signature of get_val
visible in definition, , still have function callable lambda?
you can check whether callable convertible std::function<t(t)>
:
template<class t, class f> std::enable_if_t<std::is_convertible<f, std::function<t(t)>>::value, t> f(t v, f fn) { return fn(v); }
Comments
Post a Comment