【发布时间】:2016-03-29 16:31:58
【问题描述】:
假设我们有这样一个示例类:
class Union {
union Value {
int i;
float f;
};
enum class Type {
Int, Float
};
Type type;
Value value;
public:
operator int&() { return value.i; }
operator float&() { return value.f; }
template <typename T, is_arithmetic<T>>
operator T() const {
if (type == Type::Int)
return static_cast<T>(value.i);
else
return static_cast<T>(value.f);
}
}
我想允许将 Union 实例转换为任何算术类型,但禁止将其转换为引用,除了示例中的 int 和 float 类型。对于给定的示例,编译器会通知存在多个转换。如何处理这样的问题?有没有可能?
【问题讨论】:
标签: c++ casting operator-overloading