1

I am currently trying to create a vector containing function of a class .

Here is my code :

typedef leap::float64 (DataReader::*getFonction)();

std::vector<getFonction> vec;
std::vector<getFonction>::iterator it;

vec.push_back(&DataReader::getLa);
vec.push_back(&DataReader::getLon);

for(it = vec.begin(); it<vec.end(); it++)
    std::cout << *it << std::endl;

The function "get ..." (not static ) returned values ​​are stored on shared resources and already initialized. But then , they return me only the values ​​'1'.

An idea?

Mercer
  • 9,736
  • 30
  • 105
  • 170

1 Answers1

5

When you dereference it and output it, you are just printing out a representation of the function pointer, which is being implicitly converted to bool and output as 1 because it is not null.

If you want to call the function and output the return value, you need to call it on an instance:

DataReader reader;

for(it = vec.begin(); it<vec.end(); it++)
    //dereference it to get member function pointer and call it on reader
    std::cout << (reader.*(*it))() << std::endl;

If you are using C++11, std::function may be better suited:

using getFunction = std::function<leap::float64(DataReader&)>;

std::vector<getFunction> vec;
std::vector<getFunction>::iterator it;

vec.emplace_back(&DataReader::getLa);
vec.emplace_back(&DataReader::getLon);

DataReader reader;
for(it = vec.begin(); it<vec.end(); it++)
    std::cout << (*it)(reader) << std::endl;
TartanLlama
  • 63,752
  • 13
  • 157
  • 193