带静态类成员方法的Q_COREAPP_STARTUP_FUNCTION

问题描述:

我需要使用qRegisterMetaType()注册我的课程,并且想要使用Q_COREAPP_STARTUP_FUNCTION带静态类成员方法的Q_COREAPP_STARTUP_FUNCTION

我不想在main()注册它,因为我需要在一个(而不是静态链接)库。

void someUniqueMethodName() 
{ 
    qRegisterMetaType(MyClass*); 
} 

Q_COREAPP_STARTUP_FUNCTION(someUniqueMethodName) 

我有多个这种情况,我不想污染根命名空间。编译器不需要具有相同名称的多个方法,我不想在每次添加新方法时考虑唯一的方法名称。

因此,我的类中的静态成员方法!

但是这个例子不能编译:

class MyClass { 
public: 
    // ... 
    static void registerMetaType(); 
} 

在.cpp文件中FPGA实现:

MyClass::registerMetaType() {} 

Q_COREAPP_STARTUP_FUNCTION(MyClass::registerMetaType) 

为什么我不能用静态成员方法,如果这是不正确的解决这个问题的方法是什么?

UPDATE 编译器错误信息:

/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) 
+0

你能后的编译器错误?也许你需要'Q_COREAPP_STARTUP_FUNCTION(&MyClass :: registerMetaType)' – drescherjm

+0

有和没有'&'的编译错误。查看我的问题中的更新。 –

我报告功能要求为Qt来增加对成员函数: https://bugreports.qt.io/browse/QTBUG-66902

貌似问题是在静态成员函数::和宏的用法。

反正替代解决方案,以克服“污染根命名空间”和重复的符号,是使用命名空间:

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