我有一个自定义类型,描述为
struct A {
double dbl_;
bool boo_;
operator double() const { return dbl_; }
//operator bool() const { return boo_; }
};
现在我想将其转换为简单类型。当 operator bool()
未定义时,a
可以隐式转换为任何简单类型 int、unsigned、float 等。但是使用 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 with restricted types 。
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.在dbl_
中保存bool
值,因为只使用其中一个。不酷,对我来说。
可能存在更完善的解决方案?喜欢
operator bool() const no_implicit_conversation_to_other_types_specifier { return boo_; }
问题最多是C++的理论。
更新 no_implicit_conversation_to_other_types_specifier 是显式
explicit operator bool() const { return boo_; }
Run .
最佳答案
使所有转换运算符显式(以防止隐式转换)将是一个好的开始:
struct A {
double dbl_;
bool boo_;
explicit operator double() const { return dbl_; }
explicit operator bool() const { return boo_; }
};
我不确定,但我想这也有助于避免歧义。
关于c++ - 转换不明确。标准隐式转换无法选择强制转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35275605/