如何要求显式强制转换
How to require an explicit cast
本文关键字:转换 更新时间:2023-10-16
我有以下错误:
error: use of overloaded operator '+' is ambiguous (with operand types 'InObj' and 'class PerformObj')
原因是我为PerformObj
提供了vector<int>
转换运算符,以便将结果存储在向量中。然而,问题是,因为InObj
期望vector<int>
在右侧,所以它隐式地转换PerformObj
,从而导致问题。我希望PerformObj
只能显式转换为vector<int>
(加上为可读性添加的符号)。
x is an integer
nums is a vector<int>
cube is a lambda
((x + in + nums) + perform + cube)
^inobj ^ implicitly converted to vector<int>
^performobj
如您所见,PerformObj
将InObj
作为左侧参数,但添加转换运算符会导致歧义。
理想情况下,我想要这样的东西:
std::vector<int> results = static_cast<vector<int>>(x in num perform cube);
供参考,这里是代码:
InObj& operator+(InObj& lhs, const std::vector<int>& rhs) {
lhs.rhs = rhs;
return lhs;
}
class PerformObj {
public:
// snip
operator std::vector<int>() const {
std::vector<int> temp;
for (int i = 0; i < lhs.rhs.size(); i++) {
temp.push_back(rhs(lhs.rhs[i]));
}
return temp;
}
friend std::ostream& operator<<(std::ostream& os, const PerformObj& po);
} performobj;
PerformObj& operator+(const InObj& lhs, PerformObj& rhs) {
rhs.lhs = lhs;
return rhs;
}
// Error occurs on the following line
std::cout << x in nums perform cube << std::endl;
我相信这个问题的标题中的答案是正确的:在类型转换运算符上使用explicit
关键字。
更多信息:http://www.parashift.com/c++-faq/explicit-ctors.html
但是,您需要C++11。更多内容:强制转换运算符可以显式吗?
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中使用nlohmann从类到json的转换
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 复制列表初始化的隐式转换的等级是多少
- 正在将指针转换为范围
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 是否可以从int转换为enum类类型
- 了解 GLM- openGL 中的相机转换
- 将无符号char*转换为std::istream*C++