Higher order functions

I just felt like, first of all, sharing my example code for a sort of template/class based method for what are sort of higher order functions.

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
#include <iostream>
using namespace std;

template<typename func,typename out>
class funcx2
{
public:
    out f(int x)
    {
        func r;
        return r.f(x*x);
    }
};

class minusone
{
public:
    int f(int x)
    {
        return x-1;
    }
};

int main()
{
    funcx2<minusone,int> f;
    cout << f.f(8) << endl;
}


Yes, you saw that right. Objects that only contain methods.

Also, I'd like to ask, has anyone done this a different way?
closed account (zb0S216C)
Whovian wrote:
"Yes, you saw that right. Objects that only contain methods."

That's called an interface. They are usually implemented in this way:

1
2
3
4
5
6
struct Interface
{
    virtual ~Interface() { }

    virtual void Function() = 0;
};

Though, the problem with your code is that funcx2 relies on func having a function called f().

Wazzak
Yea, that's sort of how this code relies on having "functions" that accept other "functions" (technically classes/interfaces, as you said) to be able to operate on them. Because I can't just call func f(func g) as if func were a data type or anything of the sort. So instead I declared a new range of classes that are effectively functions.
Last edited on
Because I can't just call func f(func g) as if func were a data type or anything of the sort.


Actually, you can with C++11 (and in C++03 you could already use the () operator so you could get pretty far with templates):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <functional>

int callFunction(std::function<int(int)> func, int arg) {
      return func(arg);
}

int someFunc(int x) {
      return x/2;
}

struct {
    int operator()(int x) { return 2*x;}
} MyFunObject;

int main() {
     std::cout << callFunction([](int x){return x*x;}, 2) << std::endl
                     << callFunction(someFunc, 2) << std::endl
                     << callFunction(MyFunObject, 2) << std::endl;
      return 0;
                    
}



4
1
4
Last edited on
Topic archived. No new replies allowed.