Class with function parameter problem

So it could be problem with implementation or with my logic in general. Code is pretty short and it can not compile. "Operation" takes one function as 3 parameter and return whatever that function does with first 2 parameters.
Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template<class T, class F>
class Object {
public:	
	T Add(T a, T b) { return a + b;	}
	T Sub(T a, T b) { return a - b; }
	T Operation(T a, T b, F f) {
		return f(a, b);
	}
};

int main() {
	Object<int, int> o; //I know that my first 2 parameters are integers and that function Add will return int
	cout << o.Operation(3, 5, o.Add);


	return 0;
}
Last edited on
Pointer to member function: http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=142

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
#include <iostream>
#include <string>

class Object {

    public:

        template < typename T > T Add(T a, T b) const { return a + b; } // make this a static member?

        template < typename T > T Sub(T a, T b) const { return a - b; } // make this a static member?

        template < typename T, typename PTR_MEMBER_FN >
        T Operation( T a, T b, PTR_MEMBER_FN ptr_member_fn ) { 

            return (this->*ptr_member_fn)(a, b);
        }
};

int main() {

    Object o;

	std::cout << o.Operation( 3, 5, &Object::Add<int> ) << '\n' ;

	std::cout << o.Operation( 3.2, 5.4, &Object::Add<double> ) << '\n' ;

    using namespace std::literals ;
	std::cout << o.Operation( "Hello "s, "World"s, &Object::Add<std::string> ) << '\n' ;
}

http://coliru.stacked-crooked.com/a/182087d3c18e300c
Topic archived. No new replies allowed.