overloading

Hello is there any possible way to overload [] in order to take functions?
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
How's this?

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
28
29
30
31
32
33
34
35
36
#include<iostream> 
#include<functional>
#include<algorithm>
  
 
class Stringer 
{ 
private: 
  std::string m_string = "Beans!";
  
public: 
    
  void operator[] (std::function<void(std::string)> func)
  {
    func(m_string);
  }
};


void print(std::string input)
{
  std::cout << input << '\n';
}

void printBackwards(std::string input)
{
  std::reverse(input.begin(), input.end());
  std::cout << input << '\n';
}
			 
int main()
{
  Stringer stringer;
  stringer[print];
  stringer[printBackwards];
}


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';
}

15.5

(basically the same idea, passing a function pointer)
Last edited on
I see but can you put arguements for ex
double& result = loto[my_func(2),my_func(3)];
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
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.
You can implement operator, for the result type of my_func.
Last edited on
Topic archived. No new replies allowed.