问题
I'm trying to write a templated class that holds a reference to an object of it's template parameter type, and a pointer to a void returning no arg member function of that class. However I'm getting an error about '<unresolved function type>'
when I compile.
template<class T>
class memberAction
{
public:
memberAction(void (T::*func)() , T& object);
private:
void (T::*m_func)();
T& m_object;
};
template<class T>
memberAction<T>::memberAction(void (T::*func)() , T& object)
{
m_func = func;
m_object = object;
}
class File
{
public:
File();
void TELUNUS_Open();
//memberAction<File>& getOpenAction();
private:
memberAction<File> m_OpenAction;
};
File::File():
m_OpenAction(TELUNUS_Open,*this)//Line with error on it
{
}
void File::Open()
{
//
}
compiling with g++ 4.7.2 I get the following error message:
StackOverloadErrorExample.cpp|31|error: no matching function for call to 'memberAction<File>::memberAction(<unresolved overloaded function type>, File&)'|
It seems other people with a similar compiler error are confusing pointers to global functions with pointers to member functions, but I specifically declare the constructor as taking a pointer to a member function of it's template parameter, and pass it a member function of the correct type.
So how do I resolve this compiler error?
回答1:
I believe you need to pass &File::TELUNUS_Open
—or &File::Open
, whichever name you’ve actually called it—to get the member function pointer. Open
has the function type void (File::)()
whereas &File::Open
has the type you really want, the function pointer type void (File::*)()
. Beyond that, you’re going to have issues with the m_object
reference member. The assignment operator will try to assign to an uninitialised reference:
template<class T>
memberAction<T>::memberAction(void (T::*func)() , T& object)
{
m_func = func;
m_object = object;
}
You should use a constructor initializer list instead:
template<class T>
memberAction<T>::memberAction(void (T::*func)() , T& object)
: m_func(func),
m_object(object) {}
回答2:
This compiles, I believe:
template< class T >
class memberAction
{
public:
memberAction( void (T::*)(), T& );
private:
void (T::*m_func)();
T& m_object;
};
template< class T >
memberAction< T >::memberAction( void (T::*func)(), T& object )
: m_func( func ), m_object( object )
{
}
class File
{
public:
File();
void TELUNUS_Open()
{
return;
}
//memberAction<File>& getOpenAction();
private:
memberAction< File > m_OpenAction;
};
File::File()
: m_OpenAction( &File::TELUNUS_Open, *this ) //Line with error on it
{
}
来源:https://stackoverflow.com/questions/15845230/unresolved-overloaded-function-type