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