2

I have the following code in my Individual.hpp file:

typedef string (Individual::*getMethodName)(void);    
static getMethodName currentFitnessMethodName;
static string getCurrentFitnessMethodName();

And this on my .cpp file:

string Individual::getCurrentFitnessMethodName(){
    return (Individual::*currentFitnessMethodName)();
}

I'm using function pointers in other parts of my code but always in the same object context, so I do (this->*thingyMajigger)(params), but with that static call I get the following error:

Expected unqualified-id

I have tried multiple permutations of said code but none seem to work. Can anyone share some light?

Cheers

4
  • Being a pointer to non-static member function, currentFitnessMethodName requires an Individual object to be called on. In your static function getCurrentFitnessMethodName, there is no this pointer. Do you have another Individual object you can use there? Commented Jun 9, 2017 at 21:51
  • Why are you using static and function pointer instead of just doing it correctly with object.method? Commented Jun 9, 2017 at 22:14
  • @aschepler, no I don't. I just described that as an example. Commented Jun 9, 2017 at 22:59
  • @stark because the value of that pointer is variable depending on certain params. And since the point is not needing the object to use this function, I can't do that Commented Jun 9, 2017 at 23:02

1 Answer 1

2

Your typedef is what's messing you up. Static methods are just regular functions that just happen to have access to protected/private static members of their class.

Change the typedef to simply:

typedef string (*getMethodName)(void);

The former syntax is for non-static member methods.


As an example, the following doesn't compile:

#include <iostream>
#include <string>

using namespace std;
class Foo {
public:
    typedef string (Foo::*staticMethod)();

    static staticMethod current;

    static string ohaiWorld() {
        return "Ohai, world!";
    }

    static string helloWorld() {
        return "Hello, world!";
    }

    static string callCurrent() {
        return Foo::current();
    }
};

Foo::staticMethod Foo::current = &Foo::ohaiWorld;

int main() {
    cout << Foo::callCurrent() << endl;
    Foo::current = &Foo::helloWorld;
    cout << Foo::callCurrent() << endl;
    return 0;
}

But changing the typedef from

typedef string (Foo::*staticMethod)();

to

typedef string (*staticMethod)();

allows it to compile - and as expected it outputs:

Ohai, world!
Hello, world!
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.