c++ - 具有静态类成员方法的 Q_COREAPP_STARTUP_FUNCTION

标签 c++ qt qcoreapplication

我需要使用 qRegisterMetaType() 注册我的类(class),并且想使用 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)

最佳答案

我已经报告了 Qt 添加对成员函数的支持的功能请求: https://bugreports.qt.io/browse/QTBUG-66902

看起来问题出在静态成员函数中的 :: 和宏的使用上。

无论如何,克服“污染根 namespace ”和重复符号的替代解决方案是使用 namespace :

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

关于c++ - 具有静态类成员方法的 Q_COREAPP_STARTUP_FUNCTION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44675055/

相关文章:

c++ - 关于 cin.get() 的说明

c++ - 构造函数参数的条件

c++ - 使用 horizo​​ntalSlider 旋转椭圆时出现 Qt QPainter 错误

c++ - 在 QThread 中的 QCoreApplication 上调用 quit() 时出错

c++ - QEventLoop 处理所有事件

windows - 在c/c++中使用检查函数编译Windows NT命令行代码循环

c++将dll注入(inject)cmd.exe监控命令

c++ - 如何在数据更改时强制模型更新 QComboBox?

qt - 为什么我的 sqlite 查询在 Qt5 中这么慢?

c++ - 如果使用 QApplication,qApp->exec() 是否有效