samedi 21 janvier 2017

Deduce the std::function result type and use it as a parameter

This is how my simple class looks like.

template <class T>
class A {
T first;
T second;

public:
A(T f, T s) : first(f), second(s) {};

template <class F>
auto foo(F f) -> decltype(f(T(), T())) {
    return f(first, second);
}
};

int main() {
    A<int> a = A<int>(2, 3);
    a.foo([](int l, int r)->int{return l + r;});
}

I want foo to take a function (or lambda or fucntion pointer) f that takes two attributes of type T and return the result of f().

This code works, but I create dummy arguments to get result of decltype. In this case those are simple integers, but it can be anything, and I certainly don't want to construct dummy parameters from bigger classes. How to deal with that?

Moreover, this is just a simplified case. In my case foo looks like that:

foo(function f, result_type_of_f t1, result_type_of_f t2) {
    // do something
    return f(first, second, t1, t2);
}

I couldn't do it with methods similar to the first one, I also tried methods from this post Determining return type of std::function but to no avail.

Aucun commentaire:

Enregistrer un commentaire