4

我需要使用qRegisterMetaType()并想使用Q_COREAPP_STARTUP_FUNCTION来注册我的课程。

我不想在其中注册它,main()因为我需要在(非静态链接的)库中使用它。

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

Q_COREAPP_STARTUP_FUNCTION(someUniqueMethodName)

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

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

但是这个例子没有编译:

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

在 .cpp 文件中实现:

MyClass::registerMetaType() {}

Q_COREAPP_STARTUP_FUNCTION(MyClass::registerMetaType)

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

更新 编译器错误消息:

/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)
4

1 回答 1

1

我已经报告了 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
于 2018-03-06T12:54:18.500 回答