Get Pointer of Funct in Struct

closed account (o1vk4iN6)
I was wondering if there was a way to initialize a function and place a pointer within a struct so that I can in some effect create a macro to create a function, rather than having two separate macros (one for function, one for array).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

struct FunctPtr 
{
     // other data here

     void (* funct)(A*);
};

class A {
public:
     int name1, name2;
     FunctPtr a[];
};

#define MACRO_FUNCT_ARR( name ) \
     { void ##name(A* a){ /*do something */ } }

FunctPtr A::arr[] =
{
    MACRO_FUNCT_ARR(name1),
    MACRO_FUNCT_ARR(name2)
};



I know java supports syntax which allows the overriding of a function in a new operator:

1
2
3
4
5
6
7
8
9
10
// java

new ActionListener() 
{
	// override function
	public void actionPerformed(ActionEvent arg0) { 
		// button press operation
	}
}
Last edited on
I could be wrong, but it sounds like you want a functor? Not sure because your macro doesn't make sense to me. See a functor example:

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
class MyFunctor
{
    int *_theData;

public:
    MyFunctor(int *data) : _theData(data)
    { }

    //Operator() overload:
    void operator()(/* Some other parameters here, if needed */)
    {
        //Do something with the data.
        ...
    }
};

//Then create functors and use them.
int main()
{
    int array1[] = { 1, 2, 3 };
    int array2[] = {4, 5, 6 };
    MyFunctor functors[] = { MyFunctor(array1), MyFunctor(array2) };
    //Call the functors.
    for (int i = 0; i < _countof(functors); i++)
    {
        functors[i]();
    }
    return 0;
}
I could be wrong, but it sounds like he wants a lambda function? See http://www.cprogramming.com/c++11/c++11-lambda-closures.html
closed account (o1vk4iN6)
Yes lambda functions is what I needed, thank you.

edit:

Seem to be unable to convert to a pointer to a function (visual studio only bug?), is there any way to define a variable to take a lambda like I would in a structure for a function pointer?

1
2
3
4
5
6
7
8
9
10
11
12

struct A
{
       void (* funct_ptr)();

      // somehow define a lambda variable here instead ? is there syntax for this?
};

A a = { 
     [] () { /* do something */ } // error unable to convert "lambda [] void -> void" to void (*)()
}; 
Last edited on
Topic archived. No new replies allowed.