Reputation: 3796
I need to register my class using qRegisterMetaType()
and wanted to use Q_COREAPP_STARTUP_FUNCTION.
I dont want to register it in main()
because I need this in a (not statically linked) library.
void someUniqueMethodName()
{
qRegisterMetaType(MyClass*);
}
Q_COREAPP_STARTUP_FUNCTION(someUniqueMethodName)
I have multiple cases for this and I dont want to pollute the root namespace. The compiler does not want multiple methods with the same name and I dont want to think about unique method names every time I am adding a new one.
Hence the static member method in my classes!
But this example does not compile:
class MyClass {
public:
// ...
static void registerMetaType();
}
with the implemention in .cpp file:
MyClass::registerMetaType() {}
Q_COREAPP_STARTUP_FUNCTION(MyClass::registerMetaType)
Why can't I use static member methods and if this isn't the correct way to solve this, what would be a better one?
UPDATE Compiler error messages:
/path/to/myclass.cpp:183:1: error: no ‘void MyClass::registerMetaType_ctor_function()’ member function declared in class ‘MyClass’
Q_COREAPP_STARTUP_FUNCTION(MyClass::registerMetaType)
^
In file included from /path/to/qt5-5.6.0/include/QtCore/QtGlobal:1:0,
from /path/to/myclass.h:18,
from /path/to/myclass.cpp:15:
/path/to/myclass.cpp:183:1: error: qualified name does not name a class before ‘{’ token
Q_COREAPP_STARTUP_FUNCTION(MyClass::registerMetaType)
^
/path/to/myclass.cpp:183:1: error: invalid type in declaration before ‘;’ token
Q_COREAPP_STARTUP_FUNCTION(MyClass::registerMetaType)
^
/path/to/myclass.cpp:183:1: error: definition of ‘MyClass::registerMetaType_ctor_function_ctor_instance_’ is not in namespace enclosing ‘MyClass’ [-fpermissive]
/path/to/myclass.cpp:183:1: error: ‘static’ may not be used when defining (as opposed to declaring) a static data member [-fpermissive]
/path/to/myclass.cpp:183:1: error: ‘const int MyClass::registerMetaType_ctor_function_ctor_instance_’ is not a static member of ‘class MyClass’
/path/to/myclass.cpp:183:28: error: uninitialized const ‘MyClass::registerMetaType_ctor_function_ctor_instance_’ [-fpermissive]
Q_COREAPP_STARTUP_FUNCTION(MyClass::registerMetaType)
Upvotes: 4
Views: 606
Reputation: 555
I have reported feature request for Qt to add support for member functions: https://bugreports.qt.io/browse/QTBUG-66902
Looks like issue is with ::
in static member function and usage of macros.
Anyway, alternative solution to overcome "polluting root namespace" and duplicate symbols, is to use namespaces:
namespace { // no duplicate symbol across units
namespace detail { // avoid "polluting" global namespace of this .cpp file
void registerMetaTypes() {
qRegisterMetaType(MyClass*);
}
Q_COREAPP_STARTUP_FUNCTION(registerMetaTypes)
} // namespace detail
} // anonymous namespace
Upvotes: 1