0

Here's what I'm attempting to do, it seems to compile, but I'm unable to get my calling code to compile OptionalFunctionTwo :

#include <functional>
#include <iostream>
#include <string>
#include <tuple>

void OptionalFunction(bool Enabled,
    std::function<void()> MyFunction) {
  if (Enabled) {
    MyFunction();
  }
}

template<typename ...Args>
void OptionalFunctionTwo(bool Enabled, std::tuple<Args...> Arguments, std::function<void(Args...)> MyFunction) {
  if (Enabled) {
    MyFunction(Arguments);
  }
}

int main(int argc, char** argv) {
  auto TestLambda = [](std::string Message) { std::cout << Message << std::endl; };

  std::string Message = "Hello World";
  OptionalFunction(true, std::bind(TestLambda, Message));

  OptionalFunctionTwo(true, std::make_tuple(Message), TestLambda);

  return 0;
}

The bind version works, but I'm wondering if there's a cleaner way to achieve the same effect without the bind, or the tuple. I can't even get the tuple to work for the clalling code so even knowing what's going on there would be interesting.

Here are the errors I'm seeing:

error C2672:  'OptionalFunctionTwo': no matching overloaded function found
error C2784:  'void OptionalFunctionTwo(bool,std::tuple<_Types...>,std::function<void(Args...)>)': could not deduce template argument for 'std::function<void(Args...)>' from 'main::<lambda_58265157e572a7c9669a130a4f982446>'
message :  see declaration of 'OptionalFunctionTwo'
Lockyer
  • 1,311
  • 1
  • 13
  • 30
  • 1
    Does `OptionalFunctionTwo(true, std::make_tuple(Message), TestLambda); ` work? Sometimes template deduction is just too complex and you have to specify the arguments explictly. – Remy Lebeau Oct 16 '19 at 21:21
  • 1
    @RemyLebeau It can't work. A lambda is not a `std::function` so deduction will always fail. – NathanOliver Oct 16 '19 at 21:23
  • 1
    Also `MyFunction(Arguments)` needs to be `std::apply(MyFunction, Arguments)` (C++17 or make your own or use parameter pack directly without the tuple). – LogicStuff Oct 16 '19 at 21:25
  • Does [this](https://stackoverflow.com/a/53326317/10957435) help? –  Oct 16 '19 at 21:31

0 Answers0