派生类和模板参数

Derrived Classes and Template Arguments

本文关键字:参数 派生      更新时间:2023-10-16

对不起,标题含糊不清。

我试图在一个相当大的代码库中解决一个问题。该修复程序要求我将ChildClassChildListElementClass都作为模板参数与另一个一起提供。我相信我遇到的问题是ParentListElementClass中的myType没有被派生类ChildListElementClass中的typedef ChildClass<ChildListElementClass> myType;覆盖。我怎样才能做到这一点?谢谢!

编译器 说:

Error   1   error C2664: 'void ParentListElementClass<ChildClass>::AddX(ParentClass<ParentListElementClass<ChildClass>> *)' : cannot convert argument 1 from 'ParentClass<ChildListElementClass> *const ' to 'ParentClass<ParentListElementClass<ChildClass>> *'

写了以下最小的测试用例来演示我的问题:

#include "stdafx.h"
#include <iostream>
template <class ElementType>
class ParentClass;
template <class ParentType>
class ParentListElementClass
{
public:
    ParentListElementClass(){};
    ~ParentListElementClass(){};
    typedef ParentClass<ParentListElementClass> myType;
    myType *x;
    void AddX(myType *m){
        m->speak();
    };
};

class ChildListElementClass;
template <class ElementType>
class ParentClass
{
public:
    ParentClass(){};
    ~ParentClass(){};   
    ElementType m;
    void DoSomething() {
        std::cout << "ParentListn";
        m.AddX(this);
    }
    virtual void speak(){ std::cout << "Parentn";}
};

class ChildClass;
class ChildListElementClass : public ParentListElementClass<ChildClass>
{
public:
    ChildListElementClass(){};
    ~ChildListElementClass(){};
};

class ChildClass : public ParentClass<ChildListElementClass>
{
public:
    ChildClass(){};
    ~ChildClass(){};
    void speak(){ std::cout << "Childn"; }
};

int _tmain(int argc, _TCHAR* argv[])
{
    ChildClass Child;
    ChildListElementClass ChildListElement;
    Child.DoSomething();
    return 0;
}

编辑:在鼬的帮助下工作版本:

template <typename ElementType, typename ListType> class ParentListClass;
template <typename ElementType, typename ListType>
class ParentElementClass
{
    typedef ParentListClass<ElementType, ListType> myType;
};
template <typename ElementType, typename ListType>
class ParentListClass{};
class ChildListClass;
class ChildElementClass : public ParentElementClass<ChildElementClass, ChildListClass>{};    
class ChildListClass : public ParentListClass<ChildElementClass, ChildListClass>{};

我不确定我是否完全理解你的问题,但无论我怎么想,更改 ParentListElementClass 似乎都很难避免。你可以在这些方面尝试一些东西。

template<typename T, typename U>
struct MyTypedefCase
{
    typedef T<U> _type;
};

然后将 ParentListElementClass 重写为

template <class ParentType, typename T, typename U>
class ParentListElementClass
{
     //typedef ParentClass<ParentListElementClass> myType;     Change this to below line
     typedef typename MyTypedefCase<T,U>::_type myType;
     //Rest of your code
};

class ChildListElementClass : public ParentListElementClass<ChildClass,ChildClass,ChildListElementClass>

我从来没有用模板做过这么复杂的事情,所以我不保证它会起作用,但如果我必须以最小的更改去做,那就是这样。也许有人可以研究这个解决方案并提供更改或改进。