如何在标题和CPP之间拆分静态/模板类

How to split a static/template class between header and cpp?

本文关键字:静态 拆分 之间 标题 CPP      更新时间:2023-10-16

这是我拥有的静态/模板函数:

template<class T>
static T *createWidget(Vec pos, Module *module, ModuleWidget *moduleWidget, int paramId, float minValue, float maxValue, float defaultValue) {
    T *widget = ParamWidget::create<T>(pos, module, paramId, minValue, maxValue, defaultValue);
    moduleWidget->mRandomModeWidgets[paramId] = widget;
    widget->Module = module;
    widget->ModuleWidget = moduleWidget;
    return widget;
}

,但我想将声明放在.h上,并在.cpp上进行定义。

尝试:

template<class T>
static T *createWidget(Vec pos, Module *module, ModuleWidget *moduleWidget, int paramId, float minValue, float maxValue, float defaultValue);

和:

template<class T>
static T *MyClasss:createWidget(Vec pos, Module *module, ModuleWidget *moduleWidget, int paramId, float minValue, float maxValue, float defaultValue) {
    T *widget = ParamWidget::create<T>(pos, module, paramId, minValue, maxValue, defaultValue);
    moduleWidget->mRandomModeWidgets[paramId] = widget;
    widget->Module = module;
    widget->ModuleWidget = moduleWidget;
    return widget;
}

,但它说可能在此处未指定存储类

我在哪里错了?

,但它说可能在此处指定存储类。

我在哪里错了?

静态成员函数(是否模板(只能在类定义中声明静态。您正在尝试在类别定义之外声明静态功能静态。static关键字在类定义之外具有不同的含义。只需将其删除:

template<class T>
T *MyClasss::createWidget(params...) {
^          ^^ alśo note that there must be two colons in the scope resolution operator
  no static

还请记住,在任何翻译单元中使用的模板实例必须在定义该模板的翻译单元中实例化。这可以通过在该单独的CPP文件中的显式实例化来实现。