How to insert object into std::map while declaration

Viewed 67

Question:

I'm trying to insert instance of a class into std::map at compile time but getting the below error always.

main.cpp:18:12: error: ‘_info’ was not declared in this scope
     _info(1)
        ^

line number 18 points to below block of the code

15. std::map<std::string, Info > lookup  {
16.      {
17.        "aclk",
18.        _info(1)
19.      }
20.    };

Code:

#include <random>
#include <iostream>
#include <functional>
#include <map>

class Info{
    int _info;
public:
   Info(int info){
     _info = info;
   }   
}; 


 std::map<std::string, Info > lookup  {
  {
    "aclk",
    _info(1)
  }
};

int main()
{
   //dummy
}

Observation:

When I dynamically create the object I don't see any such errors.

const std::map<std::string, Info > lookup  {
  {
    "aclk",
    new Info(1)
  }
};

But map being const and instance being inserted with new doesn't make any sense.

1 Answers

You have to supply an object of the type Info instead of its data member _info. For example

 std::map<std::string, Info > lookup  {
  {
    "aclk",
    1
  }
};

This is valid because the class Info has a conversion constructor.

Or (if for example the constructor is explicit)

 std::map<std::string, Info > lookup  {
  {
    "aclk",
    Info(1)
  }
};
Related