gpt4 book ai didi

c++ - 如何处理相互依赖且具有模板成员的类?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:22:57 26 4
gpt4 key购买 nike

这部分与 this SO question 有关.

我有两个类,它们都是模板化的,例如:

class Base
{
public:
template< class T > void operator=(T other)
{
//irrelevant
}

Derived toDerived()
{
Derived d;
//do stuff;
return d;
}
};

class Derived: public Base
{
public:
template< class T > void foo( T other )
{
//do stuff
}
};

如您所见,两者都是模板化的,并且在 Base 类函数内部我需要创建一个 Derived 的实例。当然,现在的情况是我收到错误 Derived does not name a type。不幸的是,我不能只转发声明Derived,因为它会导致另一个错误variable 'Derived d ' has initializer but incomplete type

从我上面提到的 SO 问题,我了解到编译器需要知道所有模板参数才能正确地转发声明它。但显然我不能将 Derived 声明向上移动,因为它会导致完全相同的问题,反之亦然。

有没有办法做到这一点?

最佳答案

这个问题与模板无关。您可以只使用 Derived 的前向声明来编译 Base::toDerived() 的声明并移动函数定义取决于 Derived after Derived 定义:

// Forward declaration of Derived
class Derived;

// Definition of Base
class Base
{
public:
// Base::toDerived() declaration only
Derived toDerived();
};

// Definition of Derived
class Derived: public Base
{
public:
...
};

// Base::toDerived() definition
inline Derived Base::toDerived()
{
Derived d;
// Do dirty things
return d;
}

关于c++ - 如何处理相互依赖且具有模板成员的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12634344/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com