Reputation: 15872
Here's my class definition:
class A {
public:
void do_lengthy_work() {
cout << "working." << endl;
}
};
I have an object of type A
, and I want to call do_lengthy_work()
on it:
A a;
a.do_lengthy_work();
Is it also possible to call the same method using some variant of the following?
A::do_lengthy_work(a);
Upvotes: 0
Views: 1405
Reputation: 76531
You can wrap the function with mem_fun_ref
:
mem_fun_ref(&A::do_lengthy_work)(a);
This can be very useful for STL algorithms like for_each
:
std::vector<A> vec;
std::for_each(vec.begin(), vec.end(), mem_fun_ref(&A::do_lengthy_work));
If you have an A *
, you would use mem_fun
:
std::vector<A *> vecp;
std:for_each(vecp.begin(), vecp.end(), mem_fun(&A::do_lengthy_work));
Upvotes: 12
Reputation: 400174
The way you wrote it, no you can't do that. You could create a static overload, although I would advise against this:
class A {
public:
void do_lengthy_work() {
cout << "working." << endl;
}
static void do_lengthy_work(A& a) {
a.do_lengthy_work();
}
};
However, this can be confusing. Why do you want to do this? Why can't you just call a.do_lengthy_work()
?
Upvotes: 2
Reputation: 190907
You could do this.
static void do_lengthy_work(A& a) {
a.do_lengthy_work();
}
Upvotes: 2
Reputation: 6188
Yes, if the method is declared to be static
, meaning it does not belong to a particular instance of the class.
class A {
public:
static void do_lengthy_work() {
cout << "working." << endl;
}
};
A::do_lengthy_work();
Upvotes: 1