mercredi 7 août 2019

Convert function template into templated functor

I'm wondering whether it might be possible to create function objects from function templates. The following Functor struct creates a function object from a function:

#include <iostream>

template <typename F, F* f>
struct Functor {
  template <typename... Ar>
  auto operator()(Ar&&... rg) -> decltype(f(std::forward<Ar>(rg)...)) {
    return f(std::forward<Ar>(rg)...);
  }
};

int plus_one(int a) {
  return a + 1;
}

int main () {

  std::cout << Functor<decltype(plus_one), &plus_one>()(1) << "\n";

  return 0;
}

This creates a structure like

struct PlusOne {
  int operator()(int a) {
    return a + 1;
  }
}

Now, I'd like to work with a function template instead of a function:

template <typename T>
T plus_one(T a) {
  return a + 1;
}

which I'm hoping to turn into something like

struct PlusOne {
  template <class T>
  T operator()(T a) {
    return a + 1;
  }
};

Is this possible? One of the reasons I'm asking this is that I read generic lambda expressions in C++14 are being turned into functors similar to what I'm after:

For example, this generic lambda-expression containing statement:

 auto L = [](const auto& x, auto& y){ return x + y; };

might result in the creation of a closure type, and object that behaves similar to the struct below:

struct {
  template <typename T, typename U>
  auto operator()(const T& x, U& y) const { return x + y; }
} L;

So I was naively hoping some facilities for making possible what I'm after, might exist. I'm restricted to C++11 though.

Aucun commentaire:

Enregistrer un commentaire