29

In some situations it's desirable to be able to type-erase a callable (e.g. function, function pointer, object instance with operator(), lambda, mem_fn), for instance in Using Boost adaptors with C++11 lambdas where a copy-assignable and default-constructible type is required.

std::function would be ideal, but there seems to be no way to automatically determine what signature to instantiate the class template std::function with. Is there an easy way to get the function signature of an arbitrary callable and/or wrap it in an appropriate std::function instantiation instance (i.e. a make_function function template)?

Specifically, I'm looking for one or other of

template<typename F> using get_signature = ...;
template<typename F> std::function<get_signature<F>> make_function(F &&f) { ... }

such that make_function([](int i) { return 0; }) returns a std::function<int(int)>. Obviously this wouldn't be expected to work if an instance is callable with more than one signature (e.g. objects with more than one, template or default-parameter operator()s).

Boost is fine, although non-Boost solutions that aren't excessively complex are preferred.


Edit: answering my own question.

Community
  • 1
  • 1
ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • 1
    If you only care for lambdas then yes, you can get it to work. I'd advise against that -- I suspect that introspecting functors is somewhat of an antipattern in C++11. Make also sure that you really need `std::function`. – Luc Danton Aug 10 '12 at 02:21

3 Answers3

31

I've come up with a fairly nasty non-library solution, using the fact that lambdas have operator():

template<typename T> struct remove_class { };
template<typename C, typename R, typename... A>
struct remove_class<R(C::*)(A...)> { using type = R(A...); };
template<typename C, typename R, typename... A>
struct remove_class<R(C::*)(A...) const> { using type = R(A...); };
template<typename C, typename R, typename... A>
struct remove_class<R(C::*)(A...) volatile> { using type = R(A...); };
template<typename C, typename R, typename... A>
struct remove_class<R(C::*)(A...) const volatile> { using type = R(A...); };

template<typename T>
struct get_signature_impl { using type = typename remove_class<
    decltype(&std::remove_reference<T>::type::operator())>::type; };
template<typename R, typename... A>
struct get_signature_impl<R(A...)> { using type = R(A...); };
template<typename R, typename... A>
struct get_signature_impl<R(&)(A...)> { using type = R(A...); };
template<typename R, typename... A>
struct get_signature_impl<R(*)(A...)> { using type = R(A...); };
template<typename T> using get_signature = typename get_signature_impl<T>::type;

template<typename F> using make_function_type = std::function<get_signature<F>>;
template<typename F> make_function_type<F> make_function(F &&f) {
    return make_function_type<F>(std::forward<F>(f)); }

Any ideas where this can be simplified or improved? Any obvious bugs?

ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • +1. What `get_signature_impl` bool template parameter does? – Leonid Volnitsky Oct 05 '12 at 05:08
  • @LeonidVolnitsky it's completely unnecessary; I've removed it. I think I put it in there when I was writing `get_signature` as a recursive template but it's not needed now. – ecatmur Oct 05 '12 at 08:07
  • why put & in decltype(&std::remove_reference::type::operator())>::type ? – Guillaume Paris Apr 11 '13 at 12:40
  • @ecatmur: no sorry it seems it is mandatory at least under g++4.8 I'm just wondering why – Guillaume Paris Apr 11 '13 at 15:10
  • 1
    Ah, my mistake. The `&` is mandatory; per 5.1.1p13 the expression inside `decltype` is an id-expression denoting a non-static member function, so can only be used to form a pointer-to-member. There's no such thing as a member function type, only a pointer to member function type. – ecatmur Apr 11 '13 at 15:51
  • 1
    FWIW, with generic lambdas this will no longer work. – Rapptz Sep 08 '14 at 06:35
  • 1
    It doesn't work in the obvious cases where the signature is ambiguous (e.g. polymorphic lambdas, template `operator()` or more overloads for `operator()`). It also doesn't work if your class is not copyable but movable, even if you pass it as a temporary. It seems to be a problem with `std::function` though. – petersohn May 10 '15 at 06:43
  • Incredible. Thank you very much! – karliwson Nov 25 '17 at 07:18
2

Impossible. You may be able to take the address of operator() for some types, but not for an arbitrary callable, because it may well have overloads or template parameters. Whether or not it would work for a lambda is most assuredly not well-defined, AFAIK.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • Good point, but I'm primarily concerned with lambdas, where exactly one `operator()` exists. – ecatmur Aug 09 '12 at 23:10
  • Well, it's certainly not well-defined that that is the case, and I'm not actually sure that it's even defined that one exists. – Puppy Aug 09 '12 at 23:14
  • 5
    5.1.2:5 *The closure type for a lambda-expression has a public inline function call operator [...]* – ecatmur Aug 09 '12 at 23:16
1

For non-variadic non-generic captureless lambda functions as well as simple free functions one can use following approach:

#include <iostream>

#include <cstdlib>

template< typename L, typename R, typename ...A >
constexpr
auto // std::function< R (A...) >
to_function_pointer(L l, R (L::*)(A...) const)
{
    return static_cast< R (*)(A...) >(l);
}

template< typename L, typename R, typename ...A >
constexpr
auto // std::function< R (A...) >
to_function_pointer(L l, R (L::*)(A...)) // for mutable lambda
{
    return static_cast< R (*)(A...) >(l);
}

template< typename L >
constexpr
auto
to_function_pointer(L l)
{
    return to_function_pointer(l, &L::operator ());
}

template< typename R, typename ...A >
constexpr
auto // std::function< R (A...) >
to_function_pointer(R (* fp)(A...))
{
    return fp;
}

namespace
{

void f() { std::cout << __PRETTY_FUNCTION__ << std::endl; }

}

int
main()
{
    to_function_pointer([] () { std::cout << __PRETTY_FUNCTION__ << std::endl; })();
    //to_function_pointer([&] () { std::cout << __PRETTY_FUNCTION__ << std::endl; })(); // can't cast from non-captureless lambda to function pointer
    to_function_pointer([] () mutable { std::cout << __PRETTY_FUNCTION__ << std::endl; })();
    to_function_pointer(f)();
    to_function_pointer(&f)();
    return EXIT_SUCCESS;
}
Tomilov Anatoliy
  • 15,657
  • 10
  • 64
  • 169