Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify a return type for operator[]?

Is it possible to explicitly specify a return type for overloaded operator[]?

For example, I have an object instance with an overloaded operator [], and if I use instance["num"], I'd like it to return an int, and instance["flt"] a float (there's already type handling logic), like this:

int some_value = instance["amount_of_entries"];
float other_value = instance["percentage"];

I've tried this:

class someClass {
    template<class T> T& operator[](char* index){ ... }
};

int val = instance["int_value"];

But I get an error:

error C2783: 'T &CSettings::operator [](char*)' : could not deduce template argument for 'T'

I thought of using instance<int>["int_value"], but that's a syntax error and doesn't compile.

like image 611
rev Avatar asked Mar 02 '26 09:03

rev


2 Answers

No, there's no nice way of doing this with operator[] and operators keeping it that nice. The problem is mainly that if you are going the template way, for the return type, you'll have to explicitly call operator[]<Type>(...) and variations of this.

On the other hand you could return a generic boost::variant or boost::any that will then later casted to the proper type by the user.

like image 164
Shoe Avatar answered Mar 05 '26 05:03

Shoe


The is no way to do this easily with the operators. The syntax would look something like;

instance.operator[]<int>("int_value");

Alternatives could include returning something like any; as part of boost or the upcoming library extensions.

You could try a generically named method, e.g. setting and call it as;

int value = instance.setting<int>("int_value");

Not quite the operator syntax you wanted but could work. It is easier to specify a return on a templated function than with an operator.

like image 44
Niall Avatar answered Mar 05 '26 05:03

Niall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!