【问题标题】:Q_COREAPP_STARTUP_FUNCTION with static class member methodQ_COREAPP_STARTUP_FUNCTION 与静态类成员方法
【发布时间】:2017-06-21 11:39:07
【问题描述】:

我需要使用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)

【问题讨论】:

  • 你能发布编译器错误吗?也许你需要Q_COREAPP_STARTUP_FUNCTION(&MyClass::registerMetaType)
  • 有和没有& 的编译错误。请参阅我的问题中的更新。

标签: c++ qt qcoreapplication


【解决方案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

【讨论】:

    猜你喜欢
    • 2019-01-10
    • 2012-04-13
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    相关资源
    最近更新 更多