从 Derived Class 调用 Parent-Class 的 Template-Function

Calling Template-Function of Parent-Class from Derived Class

我有一个非常具体的问题(不要介意问我为什么要这个,解释起来会很复杂)

我想从 parent-Class 调用 Template-Function,它间接调用 Child-Class

的析构函数

我尝试实现这段代码:

Parent Class:

template <typename BaseType>         //OpcUa_NodeInstance.h
class OpcUa_NodeInstance
{
public:
    template <typename BaseTypee, unsigned PrefixID>
    static void deleteType(unsigned int ObjID);

};

template <typename BaseType> // OpcUa_NodeInstance.cpp
template <typename BaseTypee, unsigned PrefixID>
void OpcUa_NodeInstance<BaseType>::deleteType(unsigned ObjID)
{
    if (ObjID == PrefixID)
    {
        NodeManagerRoot* pNodeManagerRoot = NodeManagerRoot::CreateRootNodeManager();
        auto dummyTypeInstance = new BaseTypee(UaNodeId(PrefixID, 2),
            UaString("Dummy_AutomationDomainType"), 2, pNodeManagerRoot);
        delete dummyTypeInstance;
    }
}

Child Class:

class AutomationDomainTypeBase: // AutomationDomainTypeBase.h
    public OpcUa_NodeInstance<AutomationDomainTypeBase>
{
   public:
          template <typename BaseType, unsigned int PrefixID> 
          static void deleteType(unsigned int ObjID);
}

问题是 visual studio 显示链接器错误

Error   5   error LNK2001: unresolved external symbol "public: static void __cdecl AutomationDomainTypeBase::deleteType<class AutomationDomainTypeBase,1018>(unsigned int)"

AutomationDomainTypeBase

我猜编译器无法识别 deleteType 的实现已经在 Parent-Class 中。因为有超过 400 个 child-Classes,我正在寻找一种不在所有 children.

中实现此功能的方法

您试图定义 child class 而不包括 parent class 的第一个定义。

如果我用这两个定义编译你的代码,我没有编译错误。

但是如果我只编译 child class 定义,而不先包含 parent class 定义,我得到:

1>Time\Time_Test.cpp(625): error C2504: 'OpcUa_NodeInstance' : classe de base non définie
1>Time\Time_Test.cpp(625): error C2143: erreur de syntaxe : absence de ',' avant '<'

就像你一样。

注意:确保OpcUa_NodeInstance<BaseType>::deleteType()模板成员函数在你定义OpcUa_NodeInstance模板的头文件中正确定义(而不是仅声明)class。否则,您将在链接时得到一个未定义的符号。


新编辑:

好的,我想我得到了你需要的东西:如果你只想将 OpcUa_NodeInstance::deleteType() 用于任何 child [=44,请不要 declare/define AutomationDomainTypeBase::deleteType() =].

此外,我认为您可以简单地定义 OpcUa_NodeInstance::deleteType() 如下:

template <typename BaseType>
class OpcUa_NodeInstance
{
public:
    template <unsigned PrefixID>
    static void deleteType(unsigned int ObjID);
};