Template argument for function type in C ++

Here Wrapper::setshould be able to take any function or function object corresponding to the signature int(int), and store it in std::function. It should work with function pointers, lambdas, objects with expressions operator(), std::bindetc.

#include <functional>

struct Wrapper {
    using function_type = int(int);

    std::function<function_type> func_;

    template<typename Func> void set(Func func) { func_ = func; }
};

What would be the best form setto work in all cases? That is one of

  • set(Func func) { func_ = func; }
  • set(Func&& func) { func_ = std::forward<Func>(func); }
  • set(Func& func) { func_ = func; }
  • set(const Func& func) { func_ = func; }
+4
source share
1 answer

The simplest version:

void set(std::function<function_type> f) {
    func_ = std::move(f);
}

Integrated version:

template <class F,
    class = std::enable_if_t<std::is_assignable<std::function<function_type>&, F&&>::value>
    >
void set(F&& f) {
    func_ = std::forward<F>(f);
}

. , , std::function , , , , .

+6

Source: https://habr.com/ru/post/1653927/


All Articles