Search code examples
c++neural-network

How can I have a struct with a variable with a pointer to a non-static member function?


I am creating a project related to Neural Networks. When getting the output, I want to have a neuron call the "ReturnValue" function of all the previous neurons. I've created a neuron class with said function. I want to be able to store these function pointers in a struct (to pair it with some other applicable data values), then store this struct in a vector. InTo summarize there will be one entry in the vector for every neuron in the previous layer. Each entry will be a struct containing a function pointer and a few other things. My problem is that I can't get the pointer to the function in the first place. Below is some code to illustrate.

#include <iostream>
#include <vector>

struct previous_neuron_struct {
    double weight;
    double (*funcPtr)(); //I think that this is correct
};

class neuron {
public:
    double value;
    std::vector<previous_neuron_struct> previous_neurons_vector;

    double Return_Value() {
        return value;
    }
};

int main() {
    neuron neuron1;
    neuron neuron2;
    //I know that it would be easier to avoid pointers, but this better illustrates the environment of the actual use case.
    previous_neuron_struct* temp = new previous_neuron_struct;
    temp->weight = 0.5;
    temp->funcPtr = neuron2.Return_Value; //<- Problem is here

//Rest of code
}

Line 25 is the problematic line. No combination of asterisks or ampersands that I have come across will allow me to put the address (not the return value) of neuron2.Return_Value() into temp->funcPtr. This sample code right now will give me Visual Studio error code 0300: a pointer to a bound function may only be used to call the function. But with a slightly different combination that I have seen on some tutorial websites, neuron2.*Return_Value; I get Identifier "Return_Value" is undefined. Thanks


Solution

  • Declaring and calling member function pointers have a different syntax than for normal pointers. The syntax is as shown below:

    struct previous_neuron_struct {
        double weight;
        double (neuron::*funcPtr)();  //syntax for declaring member function pointer 
    };
    int main() {
        //other code as before
        temp->funcPtr = &neuron::Return_Value; //works now
        std::invoke( temp->funcPtr, neuron1);  //call
    
        (neuron1.*(temp->funcPtr))();//another way of calling
    }
    

    Working demo