views:

119

answers:

4

hi

I want to call member function by passing it as template parameter, without using boost is possible. Here is an example off what I tried to do,

class object { void method(); }

{
object object_instance;
...
apply<object:: method>();
...

template<class F>
void apply() { F(object_instance); } // want to call object_instance.F()
}

that does not work, so question is how do I go about binding object method to an object. Thanks

above is an example, not the real code. I have a bunch of functions differing only in name, but with many parameters, that I want to wrap around in operators.

A: 

As a member function isn't a type or integral value, you can't pass it as a template parameter. You could do what you seem to want by creating a struct which calls the member function, though having object_instance in scope in the template is rather smelly.

What are you actually trying to do?

Pete Kirkham
+5  A: 

Something like:

struct foo
{
    void bar(void) {}
};

template <typename R, typename C>
R apply(C& pObject, R (C::*pFunc)())
{
    return (pObject.*pFunc)();
}

int main(void)
{
    foo f;
    apply(f, &foo::bar);
}

this.

GMan
thanks, I was trying to do that. I have read about .* operator but this is the first time actually using it
aaa
No problem. You'll have to generate or manually write different variations to allow parameter passing. Boost.Preprocessor would help here. (Though if you're using boost you'd just use `boost::bind`. You're not using boost :P)
GMan
actually arguments are the same, applied inside apply function, so it works well for me.should have probably provided real code. Thanks again
aaa
A: 

This example is for rvalue references in c++ox. Does not work on all compilers.

class Sample
{
public:
    void fun() { cout << "Sample::fun\n"; }
};

template<typename Function>
void FunCall( Function&& f)
{
    f();
}

void RvaluesDemo()
{
    FunCall([&]
    {
        Sample().fun();
    });
}
Jagannath
What's the reason for downvote?
Jagannath
I didn't so I'm just guessing, but probably because the question isn't tagged C++0x.
GMan
@GMan: No problem.But this would be much more flexible than writing different variations to allow parameter passing.
Jagannath
Well sure, but this question simply isn't about C++0x.
GMan
+1  A: 

This is similar to your code, and will allow passing a member function as a template parameter:

class object { public: void method() {} };
object object_instance;

template<void (object::*F)()>
void apply() {
    (object_instance.*F)();
}

int main() {
    apply<&object::method>();
    return 0;
}
interjay
Wouldn't this have the problem that the method is always called on the same instance of object?
Narfanator
Yes, but that's what the original code seemed to do, so I kept it the same. The instance can be passed as a parameter to apply instead.
interjay