Reputation: 9801
Does the standard library implements a type for pointers to functions in C++ ?
I'm not happy with functors (they are more like an hack to me than a real pointer to a function), you have to create an extra object, and this is really not what I'm looking for, in C with a couple of parenthesis and a simple syntax you can declare a pointer to function, I'm looking for the same simplicity plus some useful method related to the type, for example the ability to replace the pointed function while keeping the object in a consistent state all the time.
There is something like that ? I really miss the plain old function pointers in C and in C++ AFAIK there is no such thing for methods that are members of a class or any other function.
Upvotes: 1
Views: 169
Reputation: 129324
I know this question has already been answered, and this is a "real" answer, but rather a kind of "but have you thought about this way" sort of answer.
Whilst there are certainly a lot of good uses for function pointers (and in C there is often no other alternative), and I've used pointer to member functions in a C++ Basic interpreter (to good effect and I'm happy that is a good solution).
Having said that, it is often better to use other alternatives, such as polymorphism to solve the problems.
For example, we can use an interface class to make an object have a particular behaviour:
class iface
{
public:
virtual int func1() = 0;
};
class A: public iface
{
int x;
...
public:
A(v) : x(v) {}
// from iface
int func1()
{
return x * 42;
}
};
class B: public iface
{
int x;
...
public:
B(v) : x(v) {}
// from iface
int func1()
{
return x * 17;
}
};
vector<iface*> list;
int main()
{
list.push_bacK(new A(12));
list.push_back(new B(15));
for(i : list)
{
cout << i->func1() << endl;
}
}
Upvotes: 1
Reputation: 385104
If you're asking for pointers-to-member-functions, these exist as part of the core language, though I wouldn't call them "simple":
#include <iostream>
struct T
{
T(int x) : x(x) {};
void foo() { std::cout << x; }
private:
int x;
};
int main()
{
typedef void (T::*P)();
P fooptr = &T::foo;
T obj(5);
(obj.*fooptr)(); // Output: 5
}
std::function
, when combined with std::bind
, is a somewhat nicer alternative:
#include <iostream>
#include <functional>
struct T
{
T(int x) : x(x) {};
void foo() { std::cout << x; }
private:
int x;
};
int main()
{
using namespace std::placeholders; // for _1, _2, _3...
std::function<void()> f = std::bind(&T::foo, _1); // or auto f = ...
T obj(5);
f(obj); // Output: 5
}
I recommend reading up on this topic a bit further as it's not a direct equivalent, but allows you to bind a functor to a member function, with early or late binding for the this
pointer.
Upvotes: 5
Reputation: 146910
There is a function pointer type shipped with the language- Ret(*)(Args...)
. There is also a member function pointer type Ret(T::*)(Args...)
(although they're virtually worthless). In addition, you can use std::function
, std::bind
, and lambdas.
Upvotes: 1