Variadic Lambda Functions

Oct 2, 2018 at 7:47pm
Hi all,
I'm trying to write a code in which I define inside the main a lambda function which, having in input a variable number of parameters (cstdarg library), modifies an object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <vector>
#include <cstdarg>

using namespace std;

class Model_Class
{
public:
    class Parameter_Class
    {
    public:
        double Value;
        void (*Function)(Model_Class& Model, ...);
    };
    vector<Parameter_Class> Parameters;
};
int main()
{
    Model_Class Model;
    Model.Parameters.emplace_back();
    Model.Parameters[0].Function = [](Model_Class& Model, ...)
    {
        va_list Variables_List;
        va_start(Variables_List,Model);
        va_end(Variables_List);
        Model.Parameters[0].Value = 2;
    };
    Model.Parameters[0].Function(Model);
    cout << Model.Parameters[0].Value << endl;
    cout << "Hello world!" << endl;
    return 0;
}

The problem occurs only when I add the ..., va_list, va_start, va_end lines.
I don't know why but it doesn't work. Can someone help me?
Than you very much in advice.
Oct 2, 2018 at 7:52pm
Define "doesn't work".
Oct 2, 2018 at 9:08pm
Doesn't work mens that the compiler stops the esecution without giving me indications. I tried both with visuale studio and codeblocks.
Formally, is the code correct?
Thank you for the answer,
I really aprecciate tour help
Oct 2, 2018 at 9:16pm
The problem is that Model is a reference type. va_start() works by using the stack address of the last non-variadic parameter to compute offsets, but since Model is a reference, you can't get that address.

1
2
3
4
5
6
7
8
9
10
11
12
13
//...
        void (*Function)(Model_Class* Model, ...);
//...

    Model.Parameters[0].Function = [](Model_Class* Model, ...)
    {
        va_list Variables_List;
        va_start(Variables_List, &Model);
        va_end(Variables_List);
        Model->Parameters[0].Value = 2;
    };
    Model.Parameters[0].Function(&Model);
//... 
Last edited on Oct 2, 2018 at 9:16pm
Oct 2, 2018 at 9:44pm
Why not a generic lambda? Is only C++11 supported?

Edit: Oh, sorry. I see that you need a pointer to it.
Last edited on Oct 3, 2018 at 12:16am
Topic archived. No new replies allowed.