1

I have some struct like bellow to get static const map:

struct SupportedPorts{
    static std::map<std::string, std::string> init()
        {
          std::map<std::string, std::string> port;
          port["COM1"] = "ttySO1";
          port["COM2"] = "ttySO2";
          port["USB"]  = "ttyUSB0";
          return port;
        }
    static const std::map<std::string, std::string> supported_ports;
};

But I have problem when I trying get some value by key. In cpp file of class Exmaple:

#include "Example.h"

const std::map<std::string, std::string> SupportedPorts::supported_ports = SupportedPorts::init();

Example::Example(){
   std::cout << SupportedPorts::supported_ports['COM1'];
}

I get error like bellow:

note: initializing argument 1 of ‘std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
       basic_string(const _CharT* __s, const _Alloc& __a = _Alloc());
error: conversion to non-const reference type ‘std::map<std::basic_string<char>, std::basic_string<char> >::key_type&& {aka class std::basic_string<char>&&}’ from rvalue of type ‘std::basic_string<char>’ [-fpermissive]
     std::cout << SupportedPorts::supported_ports['COM1'];
                                                         ^
(null):0: confused by earlier errors, bailing out
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

1 Answers1

1

The operator [] is declared for the class template std::map the following way

T& operator[](const key_type& x);
T& operator[](key_type&& x);

That is the the operator returns a non-constant reference that may not be done for a constant object. And the operator may be called only for a non-constant object because it is declared without the qualifier const.

Instead use the function at declared like

T& at(const key_type& x);
const T& at(const key_type& x) const;

Also instead of a string literal you are using a multibyte character literal in this statement

 std::cout << SupportedPorts::supported_ports['COM1'];

Write

 std::cout << SupportedPorts::supported_ports.at( "COM1" );

Here is a demonstrative program.

#include <iostream>
#include <string>
#include <map>

int main() 
{
    const std::map<std::string, std::string> supported_ports =
    {
        { "COM1",  "ttySO1" }, { "COM2", "ttySO2" }, { "USB", "ttyUSB0" }
    };
    
    std::cout << supported_ports.at( "COM1" ) << '\n';
    
    return 0;
}

The program output is

ttySO1
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335