How to access the function pointer from vector of structure

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <cstdlib>

template<typename Data_T>
class test
{
public:
	void test_func_1(const Data_T &var)
	{
		std::cout << "test_func_1: " << var << std::endl;
	}
};

template<typename Data_T>
struct example
{
	int a;
	float b;
	void (test<Data_T>::*fun_ptr)(const Data_T& a);
};

template<typename Data_T>
std::vector<example<Data_T> > get_example(const Data_T&, size_t i)
{
      std::vector<example<Data_T> > test_vect;
	static example<Data_T> example_array[] =
	{
		{1, 2, &test<Data_T>::test_func_1}
	};

for(int i=0;i<size;i++)
		test_vect.push_back(example_array[i]);
	return test_vect;

}

int main()
{
	int i = 3;
	double d = 23.78;

	test<int> a;
	test<double> b;

	(a.*get_example(int(), 0).fun_ptr)(i);
	(b.*get_example(double(), 0).fun_ptr)(d);
}


Now how can i access the fuc_ptr()?

i am doing (test_vect.*fun_ptr)(i);. But it gives error.
This line does not compute:
(a.*get_example(int(), 0).fun_ptr)(i);

Operator precedence says that:
(a.*get_example(int(), 0).fun_ptr) this will be evaluated before (i)

and within that set of brackets get_example(int(), 0) has the highest priority
and be done first and will retun a vector result

that will leave us with:
(a.*vector_result.fun_ptr)

The next highest priority is vector_result.fun_ptr which is a class member access
That will fail because a vector has no member called fun_ptr

Should be something like this:
(a.*(get_example(int(), 3)[0].fun_ptr))(i);
So with some minor modifications/corrections

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <cstdlib>

template<typename Data_T>
class test
{
public:
    void test_func_1(const Data_T &var)
    {
        std::cout << "test_func_1: " << var << std::endl;
    }
};

template<typename Data_T>
struct example
{
    int a;
    float b;
    void (test<Data_T>::*fun_ptr)(const Data_T& a);
};

template<typename Data_T>
std::vector<example<Data_T> > get_example(const Data_T&, size_t i)
{
    std::vector<example<Data_T> > test_vect;
    static example<Data_T> example_array[] =
    {
        {1, 2, &test<Data_T>::test_func_1},
    };

    //***Had to change the following code to prevent crashes**
    for(int count=0;count <i; count++) 
        test_vect.push_back(example_array[0]);
    return test_vect;

}

int main()
{
    int i = 3;
    double d = 23.78;

    test<int> a;
    test<double> b;

     
    //Note  the use of a non-zero  value to the get_example function
    //Accessing the first object in the vector -  index  [0]
     (a.*(get_example(int(), 3)[0].fun_ptr))(i); 
}
Last edited on
Topic archived. No new replies allowed.