Olumide
Olumide

Reputation: 5819

Passing pointer to member func of outer class template to nested class

I'm having difficulty passing a pointer to the member function Outer<T>::foo to the constructor of the nested class Outer as shown below (see also ideone).

template<typename T1>
struct Outer
{
    void foo()
    {
    }

    Outer() : inner( &Outer::foo )  // ERROR: compiles without &Outer::foo and Inner( F f ), below
    {
    }

    template<typename T2, void (T2::*F)()>
    struct Inner
    {
        Inner( F f )    // ERROR
        {
        }
    };

    Inner<Outer,&Outer::foo> inner;
};

int main()
{
    Outer<int> outer;
}

What am I doing wrong? I've begun to wonder if this is at all possible.

Upvotes: 1

Views: 1094

Answers (1)

Jay Miller
Jay Miller

Reputation: 2234

The problem is that you are conflating variables and template arguments. You can use constant pointers as template arguments, or you can pass variable pointers as arguments to functions.

This works:

template<typename T1>
struct Outer
{
    void foo()
    {
    }

    Outer() : inner( &Outer::foo ) 
    {
    }

    template<typename T2>
    struct Inner
    {
        // Takes a pointer at runtime to any matching signature in T2
        Inner( void (T2::*f)( ) ) 
        {
        }
    };

    Inner<Outer> inner;
};

int main()
{
    Outer<int> outer;
}

Live

or this works:

template<typename T1>
struct Outer
{
    void foo()
    {
    }

    Outer() : inner( )  
    {
    }

    // Takes a pointer at compile time to a matching function in T2
    template<typename T2, void (T2::*f)()>
    struct Inner
    {
        Inner( )
        {
        }
    };

    Inner<Outer,&Outer::foo> inner;
};

int main()
{
    Outer<int> outer;
}

Live

Upvotes: 5

Related Questions