• ### Popular Now

• 13
• 18
• 19
• 27
• 9

This topic is 3943 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I saw this mentioned in another thread a few pages back. If this should be moved/modified moderators, please do so. Anyway, I saw someone writing their own class and there were various suggestions to get rid of the is/get functions (for example: getScore, isAlive, getName, etc.) and replace it with operator overloading ([] in particular). Anyway, I was trying to think through this for my own application but I am getting hung up on the return types. I know I am not allowed to do this:
int& operator[] (string value);
string& operator[] (string value);


However, how can I go about this so I can access a score (int) with Class["Score"] and a name (string) with Class["Name"]. Is operator overloading not an option here? Can I store this information in a way that it can be accessed under one type? Am I missing something? Thanks.

##### Share on other sites
I personally think this is a *REALLY* bad idea, could you post a link to the other thread and explain why you need to access the variables using a string name and we should be able to come up with something a bit more sane.

Assuming though that there is no way you could return a boost.any or a boost.variant

##### Share on other sites
I can think of some ways, but you should probably just use the accessors. Operator overloading is meant for classes that "can be treated like arrays". Anyway, you should usually try to replace accessors with real functionality. Unfortunately this is a bit of an art, and it will require you to Think(TM) - there are few if any hard-and-fast rules.

Ways to do it anyway:

1) boost::any or boost::variant.

2) If you don't need the input to be a string, but simply some kind of unique identifier (i.e. you're not going to try to use some inputted string from the user to do the indexing), then make unique identifiers of different types, and overload accordingly. For example:

class score_t {} score;class name_t {} name;class Thing {  int m_score;  string m_name;  public:  int& operator[](score_t) { return m_score; }  string& operator[](name_t) { return m_name; }  int operator[](score_t) const { return m_score; }  const string& operator[](name_t) const { return m_name; }};// ...Thing myThing;myThing[score] += 42;string s(myThing[name]);

This should also work if you "create the types" using enumerations (in C++, unlike in C, enumerations are actual separate types).