Dec 30, 2019 at 4:18pm UTC
Hello is there any possible way to overload [] in order to take functions?
Dec 30, 2019 at 4:46pm UTC
Can you clarify your question? What does "take functions" mean?
There are two restrictions in overloading operator[].
1. Must be done inside the class definition.
2. Can only have one parameter.
Other than that, the answer is: Yes, you can.
Last edited on Dec 30, 2019 at 4:46pm UTC
Dec 30, 2019 at 4:52pm UTC
As you were typing that, I was working on:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Example program
#include <iostream>
class Lotologist {
public :
double & operator [](double (*func)(int ))
{
lotto = func(5);
return lotto;
}
private :
double lotto;
};
double my_func(int n)
{
return n * 3.1;
}
int main()
{
Lotologist loto;
double & result = loto[my_func];
std::cout << result << '\n' ;
}
(basically the same idea, passing a function pointer)
Last edited on Dec 30, 2019 at 4:54pm UTC
Dec 31, 2019 at 4:39am UTC
I see but can you put arguements for ex
double& result = loto[my_func(2),my_func(3)];
Dec 31, 2019 at 11:36am UTC
We could do, but you're clearly doing something a bit strange and crazy just for the fun of it, so why not work it out yourself?
If you're going to want different kinds of functions, templates might be the way to go.
Last edited on Dec 31, 2019 at 11:41am UTC
Dec 31, 2019 at 9:15pm UTC
double & result = loto[my_func(2),my_func(3)];
This won't work, but you can do:
double &result = loto[my_func(2)][my_func(3)]; Here loto[my_func(2)]
returns an instance of an auxilliary class that has its own [] operator.
Jan 1, 2020 at 12:35am UTC
You can implement operator, for the result type of my_func .
Last edited on Jan 1, 2020 at 12:35am UTC