转换是模棱两可的.标准隐式转换无法选择强制转换运算符
Conversion is ambiguous. Standard implicit conversion could not choose cast operator
>我有一个自定义类型描述为
struct A {
double dbl_;
bool boo_;
operator double() const { return dbl_; }
//operator bool() const { return boo_; }
};
现在我想将其转换为简单类型。当operator bool()
未定义时a
可以隐式转换为任何简单类型 int、无符号、浮点数等。但是有了operator bool()
转换是模棱两可的。
A a;
cout << (double) a << endl;
cout << (float) a << endl; //error: conversion from 'A' to 'float' is ambiguous; candidates are: A::operator bool() const; A::operator double() const
cout << (int) a << endl; // the same
cout << (char) a << endl; // the same
return 0;
cpp.sh 上的可运行代码
我知道几种解决方法:
1.为所有预期类型添加类型转换运算符。
operator int() const { return (int)dbl_; }
// and so on...
这看起来像是不好的做法。
2.使用受限制类型的模板。
template<class T, class...> struct is_any_of: std::false_type{};
template<class T, class Head, class... Tail>
struct is_any_of<T, Head, Tail...> : std::conditional<
std::is_same<T, Head>::value,
std::true_type,
is_any_of<T, Tail...> >::type
{};
template<
class T,
class = typename std::enable_if<is_any_of<T, int, float, unsigned, double>::value>::type
>
operator T() const {
if(type_ != Type::NUMBER) throw Node::Exception("not is number");
return dbl_;
}
3.bool
dbl_
保存值,因为只使用其中一个。不酷,至于我。
可能存在更精细的解决方案?喜欢
operator bool() const no_implicit_conversation_to_other_types_specifier { return boo_; }
问题至多是C++理论。
更新no_implicit_conversation_to_other_types_specifier explicit
explicit operator bool() const { return boo_; }
跑。
将所有转换运算符显式化(以防止隐式转换)将是一个好的开始:
struct A {
double dbl_;
bool boo_;
explicit operator double() const { return dbl_; }
explicit operator bool() const { return boo_; }
};
我不确定,但我想这也有助于防止歧义。
相关文章:
- 为什么选择转换运算符的重载?
- 了解转换运算符的选择C++
- C++:使用重载而不是动态强制转换通过基选择派生类
- 选择用于赋值初始化的转换函数的优先级
- 将变体、矢量<variant>和矢量<矢量<variant>>转换为我选择的等效类型
- 是否在重载选择期间未考虑默认参数的转换
- 目标 c 将块转换为选择器
- 转换是模棱两可的.标准隐式转换无法选择强制转换运算符
- 代码在嵌套开关中选择的每个情况和错误C4244在c++中从double转换为float后停止/结束
- 选择哪个数学库来转换LabView块
- 构造函数重载选择了强制转换运算符而不是结构类型
- 如果加法表达式的第一个操作数可转换为指针和整数,则选择哪个转换
- 在重载解析中,选择使用不明确转换序列的函数是否必然会导致调用格式不正确
- Gstreamer选择一个通道并转换为单声道(去交错)
- 如何选择一个特定的视口转换,同时保持之前的转换在OpenGL
- c++规范是否说明如何在static_cast/const_cast链中选择用于C风格强制转换的类型?
- 如何消除构造函数选择的强制转换
- 如何在从QVariant参数转换时选择方法重载
- 编译器选择专门用于数组的模板,但随后尝试将数组参数强制转换为指针
- "Ambigous"等效转换 - 我可以让编译器只选择任何一个吗?