如何在头文件和cpp之间拆分静态/模板类?

时间:2019-07-03 10:09:14

标签: c++ templates compiler-errors static header

这是我拥有的静态/模板功能:

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;
}

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

我在哪里错了?

1 个答案:

答案 0 :(得分:2)

  

但是它表示可能未在此处指定存储类。

     

我在哪里错了?

静态成员函数(无论是否为模板)只能在类定义中声明为静态。您试图在类定义之外将函数声明为静态。 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文件中进行显式实例化来实现。