nbo*_*eel 2 c++ casting type-conversion
我正在使用一个模板化的库,我不想修改它。即CImg。该库主要设计用于处理简单类型的模板:float、double、int 等。
在某些时候,这个库会:
CImg<T>& fill(const T val) {
if (is_empty()) return *this;
if (val && sizeof(T)!=1) cimg_for(*this,ptrd,T) *ptrd = val;
else std::memset(_data,(int)val,size()*sizeof(T));
return *this;
}
Run Code Online (Sandbox Code Playgroud)
现在我想使用这个库和一个更复杂的类作为模板参数。我的特定类是这样的,sizeof(T)!=1并且在大多数情况下,该fill函数会根据我的类的属性正确地分配val给每个元素operator=。但是, when !val,我想要一个转换运算符,它允许我的类被强制转换为 anint并产生一些值(例如,0会使上面的函数工作)。
现在,我的程序没有编译,因为它说:
error C2440: 'type cast' : cannot convert from 'const MyClass' to 'int'
Run Code Online (Sandbox Code Playgroud)
如何在不修改上述函数的情况下创建一个允许(int)my_variablewithmy_variable类型MyClass合法的运算符?
像这样使用用户定义的转换
int type;
explicit operator int()
{
return type;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1559 次 |
| 最近记录: |