0

I am declaring a map in a header file, which maps 2 strings to a function pointer in another cpp file. However, I'm getting the following error:

Error   C2440   'initializing': cannot convert from 'initializer list' to 'std::map<std::string,std::map<std::string,std::function<void (Comp::Abc::Ptr,int)>

My header file is as follows:


#include "../Comp/include/ABC.h"
#include <map>
#include <string>
#include <functional>

namespace Comp {

    std::map<std::string, std::map<std::string, std::function<void(Comp::Abc::Ptr, int)>>> myMap = {
    {"Abc1", {
        {"QType", [](Comp::Abc1::Ptr abc, int arg) { 
                     abc->setQType(static_cast<EnumTYPEDEF_Q_TYPE>(arg)); }},
    {"Counter", [](Comp::Abc1::Ptr abc, int arg) { abc->setCounter(arg); }},
    {"GroupId", [](Comp::Abc1::Ptr abc, int arg) { abc->setGroupId(arg); }},
        }},
        {"Abc2", {
        {"Type",  [](Comp::Abc2::Ptr abc, int arg) { abc->setType(arg); }},
        }},
}
       
};
  

Other files are: Abc.h

namespace Comp{

class Abc{
  virtual void setCounter(int c){}
  virtual void setType(int c){}
  virtual void setGroupId(int c){}
  virtual void setQType(EnumTYPEDEF_Q_TYPE c){}
}

class Abc1:public Abc{
  virtual void setCounter(int c);
  virtual void setGroupId(int c);
  virtual void setQType(EnumTYPEDEF_Q_TYPE c);
}

class Abc2:public Abc{
  virtual void setType(int c);
}
};

And Abc.cpp

namespace Comp{
void Abc1 :: setCounter(int c){
  //some code
}
void Abc1 :: setGroupId(int c){
  //some code
}
void Abc1 :: setQType(EnumTYPEDEF_Q_TYPE c){
  //some code
}
void Abc2 :: setType(int c){
  //some code
}
}

The map has been declared correctly, and I'm unable to understand the error.

Some of these functions take enums as input arguments, but that is handled by static cast.

I also tried using template for function pointer:

template<typename ArgType>
using MemberFunctionPtr = void (Comp::Abc1::*)(ArgType);
std::map<std::string, std::map<std::string, MemberFunctionPtr<int>>> myMap;

But this also didnt work.

float
  • 15
  • 1
  • 6
  • 1
    Can't reproduce, it compiles just fine when eliminating the first parameter https://godbolt.org/z/61dxv5jWh Please provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Jan Schultke Jun 20 '23 at 08:48
  • What Cpp standard are you using ? Nested initializer lists work since Cpp17, i believe (or 14?). – nick Jun 20 '23 at 08:53

0 Answers0