0

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

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;
  • 那么,如何使用自己的自定义运算符安全地向上转换,最好使用静态转换?

  • 为什么使用完整的 namespace::type 进行强制转换工作,但使用 typedef 失败?

4

1 回答 1

1
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(),永远不能被调用。

这种向上转换不需要强制转换 - whenthis是类型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;

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

于 2013-07-12T15:56:20.000 回答