Inferring the call signature of a lambda or arbitrary callable for "make_function"
Asked Answered
D

3

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.

Diapedesis answered 9/8, 2012 at 22:51 Comment(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.Anora
D
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?

Diapedesis answered 5/9, 2012 at 13:58 Comment(8)
+1. What get_signature_impl bool template parameter does?Rhnegative
@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.Diapedesis
why put & in decltype(&std::remove_reference<T>::type::operator())>::type ?Metalwork
@ecatmur: no sorry it seems it is mandatory at least under g++4.8 I'm just wondering whyMetalwork
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.Diapedesis
FWIW, with generic lambdas this will no longer work.Ethelda
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.Radius
Incredible. Thank you very much!Understanding
D
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.

Dynamotor answered 9/8, 2012 at 23:6 Comment(3)
Good point, but I'm primarily concerned with lambdas, where exactly one operator() exists.Diapedesis
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.Dynamotor
5.1.2:5 The closure type for a lambda-expression has a public inline function call operator [...]Diapedesis
B
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;
}
Bradford answered 21/10, 2015 at 20:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.