类将自身传递给其他类的构造函数,两者都使用模板定义
Class passing itself to constructor of other class, both defined with templates
类A
(或其特化)应该创建类B
(或其特化)的实例,其中后者有一个字段来知道是谁创建的。以下代码隔离了问题:
template <typename R>
class A {
public:
R make() { return R(this); }
};
template <typename S>
class B {
public:
S * s;
B(S * s_) : s(s_) { }
};
挑战在于模板参数的循环依赖性。一个带有前向声明的解决方案出现:
class specB;
typedef A<specB> specA;
class specB : public B<specA> { using B::B; };
据我所知,这工作正常(在程序的其余部分使用 specA
和 specB
)。但是,以下没有(缺少的using
不负责任,上面我只包括了为了找到B
的扩展构造函数):
class specA;
typedef B<specA> specB;
class specA : public A<specB> { };
它给出:
In instantiation of ‘R A<R>::make() [with R = B<specA>]’:
required from here
error: invalid conversion from ‘A<B<specA> >* const’ to ‘specA*’ [-fpermissive]
R make() { return R(this); }
^
error: initializing argument 1 of ‘B<S>::B(S*) [with S = specA]’ [-fpermissive]
B(S * s_) : s(s_) { }
^
是否有可能让它也以这种方式工作(没有-fpermissive
)?
更新:这是一个可能的解决方案(似乎有效),但对我来说看起来不对:
template <typename S>
class B {
public:
S * s;
B(void * s_) : s(static_cast<S*>(s_)) { }
};
当通过派生类调用基类的方法时,该方法this
为指向基类的指针。基类的实现无法知道从它派生的类。
在第二个示例中,将创建一个class A<B<specA>>
,并且specA
继承该类。当您调用specA.make()
时,它会调用B<specA>(this)
,this
类型为 A<B<specA>>*
。编译器抱怨作为B<specA>
的构造函数期望类型为 specA*
的参数。从基类指针到派生类指针没有简单的转换。
你可以这样做:
template<typename T>
class Alloc
{
public:
T make() { return T(*this); }
};
template<template<typename> class A>
class Type
{
private:
A<Type>* a_;
public:
Type(A<Type>& a): a_(&a) { }
};
Alloc<Type<Alloc>> a;
Type<Alloc> t(a);
相关文章:
- 当两者都调用时,删除和析构函数之间的区别?
- C++类:virtual和override,或者两者都没有
- C++工作不统一,所有变量都定义
- 无符号 int 与无符号长 两者都是 32 位,但我无法在不转换的情况下混合它们......为什么?
- 带大小参数和不带大小参数的"运算符删除":当两者都可用时,选择哪一个?
- 将字符串转换为整数。为什么会出现此错误?我想将 ID(字符串)更改为 IC(整数)。两者都是数组。顺便说一句,我仍然是初学者
- 无限循环与无限递归.两者都未定义吗?
- 共享的静音和静音之间的差异(为什么两者都存在于C 17中)
- x&=y 是否等同于 x = x &&y 如果两者都是 c++ 布尔值
- 两种模板类型的sizeof,当两者都是从一个基派生时
- 如果其中一个为真,则 && 结束循环,而不是如果两者都为真
- 如何编写两个初始化操作(一个作为默认初始化,另一个作为用户输入)?两者都是类的构造函数C++
- 要检查它是完整的二叉树还是完全二叉树,或者两者都不是
- 试图使用模数或fmod,但两者都给我的程序带来了问题
- 编译 SkyFireEMU 错误,sizeof(void *) 两者都不是
- 类将自身传递给其他类的构造函数,两者都使用模板定义
- 顶级或低级常量,或者两者都不存在
- 从一个模板类转换到另一个(两者都派生自同一基类)
- 我应该使用virtual, override,还是两者都使用?
- 如何从另一个文件中调用与另一个文件中同名的函数(当两者都包含时)