【发布时间】:2013-07-10 12:58:22
【问题描述】:
我有一个类继承自两个类,一个是我自己的基类,一个是模板类:
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 却失败了?
【问题讨论】:
-
您的类派生自
csr_matrix<int,float,cusp::host_memory>,但您尝试将其转换为csr_matrix<int,float,cusp::device_memory>。这并不是真正的向上转换——它转换为一个不相关的类型(据我所知)。 -
不,typedef 是 csr_matrix
,但你是对的,上面的代码是错误的。从 cusp::host_memory 到 cusp::device_memory 的分配是另一回事,可以从一个分配到另一个。 -
关于基于typedef的强制转换,即
auto me = *(csr_matrix*)this;:问题可能是代码中csr_matrix此时不仅指的是typedef-name,还指代了原始模板名称cusp::csr_matrix。这可能是类名注入结合继承的结果。您是否尝试过为 typedef 使用不同的名称? -
不,我马上试试
-
不,我仍然遇到错误,尽管原因可能不同
标签: c++ templates operator-overloading upcasting