C ++: generic call-functions-f-follow-by-g method?

Is it possible to have a generic method that takes two functions fand g(returning voidand receiving one type of arguments) and returns a new function that takes an argument of the same type the fand gand first apply fto pass an argument, then g?

In particular, I want to define something like this:

template <typename FunctionType>
// FunctionType is void(ArgType1 arg1, ArgType2 arg2, ..)
FunctionType CombineTwoFunctions(FunctionType f, FunctionType g) {
  // Using the lambda syntax just for illustration:
  return [f, g](ArgsOf(FunctionType) args) {
     f(args);
     g(args);
  };
}
+4
source share
1 answer

Not the most optimized code, but it works.

Using make_functionfrom this answer

template <typename ...Args>
std::function<void(Args...)> CombineTwoFunctionsHelper(std::function<void(Args...)> f, std::function<void(Args...)> g) {

  return [f, g](Args ...args) {
     f(args...);
     g(args...);
  };
}

template <typename F1, typename F2>
auto CombineTwoFunctions(F1 f1, F2 f2) -> decltype(make_function(f1)) {
  return CombineTwoFunctionsHelper(make_function(f1), make_function(f2));
}

void print1(int i, std::string s) {
    std::cout << "print1 " << i << s << std::endl;   
}

void print2(int i, std::string s) {
    std::cout << "print2 " << i << s << std::endl;   
}

int main() {
    auto fg = CombineTwoFunctions(print1, print2);
    fg(1, "test");
}

Full code at Coliru

, () , . , .


@0x499602D2 , ++ 14 eaiser

template <typename F1, typename F2>
auto CombineTwoFunctions(F1 f, F2 g) {
  return [f, g](auto&& ...args) {
     f(args...);
     g(args...);
  };
}

void print1(int i, std::string s) {
    std::cout << "print1 " << i << s << std::endl;   
}

void print2(int i, std::string s) {
    std::cout << "print2 " << i << s << std::endl;   
}

int main() {
    auto fg = CombineTwoFunctions(print1, print2);
    fg(1, "test");
}

Coliru

+2

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


All Articles