[Qt-interest] Problems with template and function pointer
Sean Harmer
sean.harmer at maps-technology.com
Thu Nov 4 16:14:10 CET 2010
On Thursday 04 November 2010 14:16:01 mario wrote:
> 2010/11/4 Sean Harmer <sean.harmer at maps-technology.com>:
> > ( *this.*m_function )();
>
> I tried...
> (this->*p)();
> //error: pointer to member type ‘void (ModuleTest::)()’ incompatible
> with object type ‘Module<ModuleTest>’
This is your clue. The following 2 options both work. Up to you which you go
for or some variation on them:
#include <QDebug>
template <typename T> class Module
{
public:
typedef void (T::*memberPtr)( );
typedef QMap<QString, memberPtr> ModuleFunctMap;
Module(){ m_object = 0; }
void caller( const QString& functName) {
if ( m_mFunctionMap.contains(functName) ) {
memberPtr p = this->m_mFunctionMap[functName];
// Cannot simply use *this.*p as *this is not a class
// of type T
// Option 1
// No dangerous assumptions. We simply call the function
// on the object we have been given.
if ( m_object )
(*m_object.*p)();
// Option 2
// Makes assumption that we can cast this to a T*
T* obj = static_cast<T*>( this );
(*obj.*p)();
}
}
protected:
T* m_object; // Only needed for option 1
ModuleFunctMap m_mFunctionMap;
};
class ModuleTest : public Module<ModuleTest>
{
public:
ModuleTest( ) {
m_object = this; // Only needed for option 1
m_mFunctionMap["randomFunctioName"] = &ModuleTest::functionToCall;
}
void functionToCall() {
qDebug() << "YEAH!";
}
};
int main(int argc, char *argv[])
{
ModuleTest test;
test.caller("randomFunctioName");
return 0;
}
HTH,
Sean
More information about the Qt-interest-old
mailing list