使用自定义强制转换运算符向上强制转换到模板类

up-casting to template class using custom cast operator

本文关键字:转换 运算符 自定义      更新时间:2023-10-16

我有一个从两个类继承的类,一个是我自己的基类,另一个是模板类:

typedef typename cusp::csr_matrix< int,
                                   float,
                                   cusp::host_memory > csr_matrix;
class CuspMatrix
: 
  public csr_matrix,
  public Matrix
{
...
}

在某个时刻,我必须做一个赋值,它将基类对象从主机复制到设备,如下所示:

cusp::csr_matrix<int,float,cusp::host_memory> A(4,3,6);
cusp::csr_matrix<int,float,cusp::device_memory> A = B;

但在我能做到这一点之前,我必须将我的this升级到它的基类csr_matrix

我尝试过使用static_cast和自定义的强制转换运算符:

operator csr_matrix()
{
  return *( cusp::csr_matrix< int,float,cusp::device_memory> *)this;
}

然而,当我尝试做实际的事情时,我从编译器中得到了大量的错误

cusp::csr_matrix<int,float,cusp::device_memory> mtx = *(csr_matrix *)this;

事实上,静态铸造在这一点上也超出了我的能力:

auto me = static_cast<csr_matrix>( *this );
cusp::csr_matrix<int,float,cusp::device_memory> mtx = me;

然而,一支没有typedef的C型霰弹枪似乎奏效了:

auto me = *( cusp::csr_matrix< int,
                               float,
                               cusp::host_memory> *)this;

但使用typedef:失败

auto me = *( csr_matrix *)this;
  • 那么,我如何使用自己的自定义运算符安全地进行铸造,最好通过使用静态铸造

  • 为什么使用完整名称空间::type的强制转换有效,而使用typedef却失败了

cusp::csr_matrix<int,float,cusp::device_memory> mtx = *(csr_matrix *)this;

此强制转换永远无法调用转换函数,因为强制转换表达式的操作数this的类型为CuspMatrix*。只有当操作数的类型为类类型时,才会考虑转换函数:

cusp::csr_matrix<int,float,cusp::device_memory> mtx = (csr_matrix)*this;

在这种情况下,csr_matrix已经是CuspMatrix的公共基类,因此永远不能调用转换函数CuspMatrix::operator csr_matrix()

这种向上转换不需要强制转换-当this的类型为CuspMatrix*并且cusp::csr_matrix<int,float,cusp::device_memory>支持从cusp::csr_matrix<int,float,cusp::host_memory>进行赋值时,您应该能够执行以下操作:

cusp::csr_matrix<int,float,cusp::device_memory> mtx = *this;

如果没有看到实际的错误消息和可编译的示例,就很难回答第二个问题。