Template parameter to member function problem

Discussion in 'C++' started by Oplec, Nov 3, 2003.

  1. Oplec

    Oplec Guest

    Hi, I have a class template that takes an argument to a class and an
    argument to a member function of the given class. I have to use
    template<class T, void (T::*MF)()> but would like to use something along
    the lines of template<class T, class MF>. Is that possible? Below is the
    code of my currently working method.

    #include <cstdlib>
    #include <iostream>

    template<class C, void (C::*MF)()>
    class A {
    public:
    A(C& o) : object_(o) { }
    void operator()() { (object_.*MF)(); }

    private:
    C& object_;
    };

    struct B {
    void f() { std::cout << "B::f()\n"; }
    };

    int main()
    {
    B b;
    A<B,&B::f> aa(b);

    // output: B::f()
    aa();

    system("PAUSE");
    }
    Oplec, Nov 3, 2003
    #1
    1. Advertising

  2. "Oplec" <> wrote...
    > Hi, I have a class template that takes an argument to a class and an
    > argument to a member function of the given class. I have to use
    > template<class T, void (T::*MF)()> but would like to use something along
    > the lines of template<class T, class MF>. Is that possible?


    Of course it's possible. Have you tried?

    The difference is that 'void (T::*MF)()' is a non-type parameter.
    You want a _type_ parameter (who knows why?). Since you're going to
    remove the way to pass the actual pointer, you have to change the
    interface of the class A so that the pointer is passed elsewhere.

    > Below is the
    > code of my currently working method.
    >
    > #include <cstdlib>
    > #include <iostream>
    >
    > template<class C, void (C::*MF)()>
    > class A {
    > public:
    > A(C& o) : object_(o) { }
    > void operator()() { (object_.*MF)(); }
    >
    > private:
    > C& object_;
    > };
    >
    > struct B {
    > void f() { std::cout << "B::f()\n"; }
    > };
    >
    > int main()
    > {
    > B b;
    > A<B,&B::f> aa(b);
    >
    > // output: B::f()
    > aa();
    >
    > system("PAUSE");
    > }


    Before we can tell you the solution, you have to tell us
    the problem. A<B,&B::f> is the current way to pass the
    pointer to a member of B. How would you like to pass it
    instead? You could do

    A<B> aa(b, &B::f);

    is that what you need? You could also do

    aa(&B::f);

    is that what you need? Don't keep us guessing.

    Victor
    Victor Bazarov, Nov 3, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page