如何处理相互依赖并具有模板成员的类
How to deal with classes that depend on each other and have template members?
这部分与这个SO问题有关。
我有两个类,它们都是模板化的,例如:
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
后的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;
}
// Declare, but do not define
class Derived;
class Base {
public:
// Declare, but do not define
// at this point Derived must be declared to be able
// to use it in the return type
Derived toDerived();
};
// Define
class Derived: public Base {
// Rest of definition
};
// At this point Derived is defined
// Define
Derived Base::toDerived()
{
// Implementation goes here
}
你可以做
class Derived;
class Base
{
public:
template< class T > void operator=(T other)
{
//irrelevant
}
Derived toDerived();
};
class Derived: public Base
{
public:
template< class T > void foo( T other )
{
//do stuff
}
};
Derived Base::toDerived()
{
Derived d;
//do stuff;
return d;
}
如您所见,它与模板无关。
此外,这种设计根本感觉不对。
相关文章:
- 如何添加依赖于类本身的模板成员变量
- 初始化依赖于子类的继承类的常量类成员
- 类成员函数参数列表是否可以依赖于模板参数?
- 依赖于类成员属性的类实例成员
- 类成员和依赖项注入的对象与引用
- 依赖注入:依赖关系需求字段/成员
- 依赖模板基础的受保护成员
- 单独库中的类成员函数定义和链接依赖项
- 依赖于依赖类型的非静态数据成员的非限定名称
- 如何让成员函数实现依赖于类的模板参数?
- 具有依赖于实现的成员函数类型的多个静态接口
- 初始化依赖于另一个类成员的类成员
- 如何处理相互依赖并具有模板成员的类
- 模板成员中的循环类依赖项
- 如何模拟依赖的成员变量
- 无法定义依赖类型定义的成员
- 如何强制依赖静态对象(包括模板成员)的初始化顺序
- 在多继承编译器的情况下访问成员变量是否依赖?如何正确地做
- 如何从 std::array<T, N>::p ointer 成员/依赖类型推断数组大小?
- 初始化C/ c++结构体的const成员…依赖于编译器的