>我有一个自定义类型描述为
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_; }
};
我不确定,但我想这也有助于防止歧义。