使用自定义强制转换运算符向上强制转换到模板类
up-casting to template class using custom cast operator
我有一个从两个类继承的类,一个是我自己的基类,另一个是模板类:
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;
如果没有看到实际的错误消息和可编译的示例,就很难回答第二个问题。
相关文章:
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 构造函数和转换运算符之间的重载解析
- 分配给转换运算符失败-C++
- 转换运算符不适用于sleep_until
- 继承模板化转换运算符
- 模板转换运算符在 clang 6 和 clang 7 之间的区别
- 如何在模板化转换运算符中消除此构造的歧义?
- 为什么选择转换运算符的重载?
- 如何避免强制转换运算符 () 和访问运算符 [] 冲突?
- 如果可能的话,C++总是更喜欢右值引用转换运算符而不是常量左值引用吗?
- 了解转换运算符的选择C++
- 多个隐式转换运算符
- 这个typedef和转换运算符语法是什么意思
- 为什么转换运算符调用复制构造函数两次,而等效函数只调用它一次
- 类模板忽略了用户定义的转换运算符(非模板不忽略)
- 为什么在std::for_each()返回时调用转换运算符
- 为什么 std::optional 的强制转换运算符被忽略了
- 使用用户定义的转换运算符推导函数模板参数
- 模板转换运算符的分辨率不明确
- 统一初始化是隐式发生的,即使 int 强制转换运算符是使用 explicit 关键字声明的.原因是什么?