mardi 18 avril 2023

Compilation error when forwarding functions with C++11: using variables from templates in lambda

This is the toy program that I try to compile:

#include <functional>

template<typename Func, typename... Args>
int do_something_1(int foo_1, Func&& func, Args&&... args, int foo_0 = 0) { 
    int var_1 = foo_0 + 2 * foo_1; 
    return std::forward<Func>(func)(var_1, std::forward<Args>(args)...);
};

template<typename Func, typename... Args>
int do_something_2(int foo_2, Func&& func, Args&&... args) { 
    int var_2 = 10 - foo_2; 
    return do_something_1(3, std::forward<Func>(func)(var_2, std::forward<Args>(args)...));
};


int main (void) {
    return do_something_2(1, [&](int var_1, int var_2) { return (var_1 * var_2); });
}

And this is the error that I get:

<source>: In instantiation of 'int do_something_2(int, Func&&, Args&& ...) [with Func = main()::<lambda(int, int)>; Args = {}]':
<source>:18:83:   required from here
<source>:13:54: error: no match for call to '(main()::<lambda(int, int)>) (int&)'
   13 |     return do_something_1(3, std::forward<Func>(func)(var_2, std::forward<Args>(args)...));
      |                              ~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:18:30: note: candidate: 'main()::<lambda(int, int)>'
   18 |     return do_something_2(1, [](int var_1, int var_2) { return (var_1 * var_2); });
      |                              ^
<source>:18:30: note:   candidate expects 2 arguments, 1 provided

It is an extended version of another toy program that gave me some troubles: Why do I get "candidate expects 2 arguments, 1 provided" compilation error when forwarding functions with C++11?

I want to multiply var2 = 10 - 1 = 9 (line 11), var1 = 0 + 2 * 3 = 6 (line 5), result = 6 * 9 = 54 (line 17)

I don't know how to solve it neither where I can find examples/tutorials in the internet.

Aucun commentaire:

Enregistrer un commentaire