mardi 26 juillet 2016

g++ does not allow to const-ify a member function that implements an std::map lookup [duplicate]

This question already has an answer here:

I have this base class map which holds some keys and an std::pair as value.

template <typename T>
class AlarmType
{

    public:
        typedef std::pair< char , const char * > alarms_t;

        const char * printAlarmValue() const
        { 
            return alarmTable[currentAlarm].second; 
        }

        char & printAlarmChar() const
        {
            return alarmTable[currentAlarm].first;
        }

    protected:
        std::map<T , alarms_t> alarmTable;
};

alarmTable is filled up in the constructors of the derived classes and never changed again. Now I am trying to implement a simple const method that lookups the char and the const char *.

the method printAlarmValue() compiles fine. But for printAlarmChar() the compiler error states:

src/alarm.hpp:103:21: error: no match for ‘operator[]’ (operand types are ‘const std::map<Threshold_types, std::pair<char, const char*>, std::less<Threshold_types>, std::allocator<std::pair<const Threshold_types, std::pair<char, const char*> > > >’ and ‘const Threshold_types’)
    return alarmTable[currentAlarm].first;
                     ^
src/alarm.hpp:103:21: note: candidates are:
In file included from /usr/include/c++/4.8/map:61:0,
                 from src/alarm.hpp:29,
                 from src/sensor.hpp:33,
                 from src/sensor.cpp:31:
/usr/include/c++/4.8/bits/stl_map.h:456:7: note: std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = Threshold_types; _Tp = std::pair<char, const char*>; _Compare = std::less<Threshold_types>; _Alloc = std::allocator<std::pair<const Threshold_types, std::pair<char, const char*> > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = std::pair<char, const char*>; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = Threshold_types] <near match>
       operator[](const key_type& __k)

So basically from what I understand, I have no access to a const std::map operator[]. If I remove the "const" from printAlarmChar() it compiles fine. But then I loose the constness. What can I do here?

BTW: I am compiling with c++11

thank you

Aucun commentaire:

Enregistrer un commentaire