How do I specify the return type for the [] operator?
Is it possible to explicitly specify the return type for an overloaded operator[]
?
For example, I have an instance of an object with an overloaded operator []
, and if I use instance["num"]
, I would have wanted him to return int
and instance["flt"]
a float
(already there is the type of processing logic), for example:
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 am getting the error:
error C2783: 'T &CSettings::operator [](char*)' : could not deduce template argument for 'T'
I thought to use instance<int>["int_value"]
but it is a syntax error and won't compile.
source to share
There is no way to do this with operators. The syntax will look something like this:
instance.operator[]<int>("int_value");
Alternatives might include returning something like any
; as part of an upgrade or upcoming library extensions.
You can try a generic method like. setting
and call it like:
int value = instance.setting<int>("int_value");
Not exactly the operator syntax you wanted, but might work. It is easier to specify a return to a templated function than using an operator.
source to share
No, there is no good way to do this using operator[]
and operators saving this. The problem is basically that if you are going to use a template, you will have to explicitly name operator[]<Type>(...)
variations for the return type as well.
Alternatively, you can return a generic boost::variant
or boost::any
, which will then be passed on to the user with the proper type.
source to share
Here is a solution that might work for you:
#include <iostream>
class someClass {
public:
template<class T> T operator[](char* index){
return T();
}
};
int main()
{
someClass foo;
std::cout << foo.operator[]<int>("some int");
std::cout << foo.operator[]<double>("some double");
int bar = 42;
std::cin >> bar;
return 0;
}
I changed it to return a reference to return an instance. And the function call is not that good, but the only way I know is to compile a function call for the templated operator [].
source to share