Alexey S. Larionov
Alexey S. Larionov

Reputation: 7927

Function of special template function

I have a structure template e.g.:

template<typename KEY_T, typename VAL_T> 
struct pair
{
    KEY_T key; VAL_T val;
};

VAL_T val may be the different (string, list or smth else) What I want is to overload the operator[] for the specified template structure pair<std::string, std::list>, and only for it. How is it possible?

P.S. I'm writing an Ini-parser and I want to access for settings like settings[Section][Key], where settings[Section] returns the pair<std::string, std::list<Entry>> and settings[Section][Key] then return the string from std::list<Entry>

Upvotes: 0

Views: 81

Answers (2)

organicoman
organicoman

Reputation: 154

you can do this instead.

template <typename KEY, typename VAL>
struct pair
{
    KEY _key;
    VAL _val;
    pair (const KEY& key, const VAL& val):
         _key(key), _val(val)
    {};
    // ... here is the trick
    friend ENTRY& get(pair<std::string, std::list<ENTRY>>& p, size_t idx)
};
ENTRY& get(pair<std::string, std::list<ENTRY>>& p, size_t idx)
{
    return p._val [idx];
};

your question is not clear, you said:

Settings[Section] -> pair <string, list<entry>>;

Settings[Section][Key]-> list<entry>;?? the whole list object??

what you are looking for can be done like this:

std::map<std::string, std::map<std::string, std::string>> Settings;
std::string my_value = Settings[Section][Key];

Settings is a map of maps:

[Color] <-- this is the section
pen = blue <-- this is the pair KEY:VALUE
border = green
canvas = black

Upvotes: 0

Class templates may be specialized, either partially:

template<typename T> 
struct pair<std::string, std::list<T>>
{
    std::string key;
    std::list<T> val;
    T& operator[](...) {
      //implement
    }
};

or fully:

template<> 
struct pair<std::string, std::list<Entry>>
{
    std::string key;
    std::list<Entry> val;
    Entry& operator[](...) {
      //implement
    }
};

As a side note, consider putting your classes in a designated namespace. Easier to manage if you ever need to work with std::pair too.

Upvotes: 2

Related Questions