c++vectorstructfunction-pointersbraced-init-list

Initialising a vector of structs containing function pointers gives "no viable overloaded '=' "


I am trying to write a chip CPU emulator and implementing its instruction table as a vector of structs where each struct contains a value and a function pointer to a particular operation. My compiler (clang++) however gives me the error:

no operator "=" matches these operands -- operand types are: std::__1::vector<A::someStruct, std::__1::allocator<A::someStruct>> = {...}

and:

no viable overloaded '='

for the line func_table = {{1,&A::func1},{2,&A::func2}};

I'm using the exact same syntax used in a similar project on GitHub but I still get these errors. It only seems to be a problem initialising with structs of non-null function pointers. I'm very new to programming with C++ so i'd love to know what I'm misunderstanding. Below is an example of the header and source file

#include <vector>

class A{

    public:
        A();
        
    private:
        
        struct someStruct{
            int a = 0;
            void (*fptr)(void) = nullptr;
        };
        std::vector<someStruct> func_table;

        void func1();

        void func2();

};
#include "tutorial.h"

A::A(){
    func_table = {{1,&A::func1},{2,&A::func2}}; // two entries here, but the table is 512 long
}

void A::func1(){
   // something
}

void A::func2(){
   // something else
}
  
int main(){
    A example;
    return 0;
}

I don't understand what these errors mean and why brace initialisation seems to have a problem with function pointers. I would really appreciate any input on this. Thanks


Solution

  • The structure definition should look like

        struct someStruct{
            int a = 0;
            void (A::*fptr)(void) = nullptr;
        };
    

    because you are trying to use member functions of the class A as initializers.

    A::A(){
        func_table = {{1,&A::func1},{2,&A::func2}};
    }
    

    That is you have to declare pointers to class members.