问题
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