C ++ member function applied to an object

I want to call a member function, passing it as a template parameter, without using boost. Here is an example of what I was trying 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()
}

which doesn't work, so the question is how do I go about binding the method of an object to an object. Thanks

Above is an example, not a real code. I have many functions that differ only in name, but with many parameters that I want to wrap in operators.

+3
source share
4 answers

Sort of:

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.

+5
source

This is similar to your code and will allow you to pass 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;
}
+1
source

Since a member function is not a type or an integer value, you cannot pass it as a template parameter. You could do what you think you want by creating a structure that calls a member function, although the presence of an object in scope in a template is pretty smelly.

What are you really trying to do?

0
source

This example is for rvalue references in C ++ ox. It 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();
    });
}
0
source

Source: https://habr.com/ru/post/1730803/


All Articles