2

I am looking for a way to convert function object to function pointer. Captureless lambda has implicit conversion that allows to:

using fptr_t = int (*)(int);
fptr_t ptr = nullptr;
ptr = [](int) { return 2; };
ptr = [](auto) { return 3; };
(*ptr)(42);

I try to do the same with old-fashioned, empty class function objects like:

struct Foo {
  int operator()(int) const { return 5; }
} foo;

Or std predicates like std::less<int>.

One way I found is to wrap call of foo with lambda. If I can assure that foo is stateless and const I dont really need this ptr and lambda-capture:

template <typename R, typename... Args>
struct to_function_pointer<R(Args...)> {
private:
  template <typename T, REQUIRES(std::is_empty<T>::value)>
  static T const& stateless_const() {
    return (*static_cast<T const*>(nullptr));
  }

public:
  using pointer = R (*)(Args...);

  template <typename U>
  pointer operator()(U) const {
    return [](Args... args) {
      return stateless_const<std::decay_t<U>>()(args...);
    };
  }
};

But here I do not know how to provide perfect forwarding, cause [](Args&&...) or [](auto&&...) cannot convert to R(*)(Args...). Such trick fails when args is noncopyable like std::unique_ptr<int>.

I know that I could use std::function, but it's kind of heavy-weight, while I am trying to get a light-weight solution.

Live example.

Any advice appreciated.

1 Answer 1

3

I believe you can simplify your to_function_pointer with just:

template <typename R, typename... Args>
struct to_function_pointer<R(Args...)> {
    using pointer = R(*)(Args...);

    template <typename U, REQUIRES(std::is_empty<U>::value && std::is_trivially_constructible<U>::value)>
    pointer operator()(U ) const
    {
        return [](Args... args) {
            return U{}(std::forward<Args>(args)...);
        }
    }
};

Few things to note. Args... will already be references or not, you're providing that signature. So forward<> will still do the same thing - the function just happens to not be a template here. Also, scrap the weird nullptr cast. That just looks bad - if we just require trivial constructibility we can just write U{} which seems way cleaner to me.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.