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

寵の児 提交于 2019-12-24 17:04:10

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/27536395/passing-pointer-to-member-func-of-outer-class-template-to-nested-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!