此代码显示了__int32
和bool
类型的基本包装器类。我的目的是用方法和自定义操作符等扩展基本类型。
每个类都有一个隐式构造函数,允许隐式地将__int32
分配给Int32
类型。这很好,直到有一个接受的函数重载-- Int32
或Boolean
。
当重载__int32
和bool
的函数编译并工作时,类作为重载的函数会导致对重载函数的模糊调用。
我的问题:是否有一种正确解决这个问题的方法,这样我就可以为基本类型实现包装类,而不存在过载解析问题,并且不需要调用者进行显式强制转换。
class Boolean
{
private:
bool _Value = false;
public:
Boolean(bool value)
{
_Value = value;
}
};
class Int32
{
private:
__int32 _Value = 0;
public:
Int32(__int32 value)
{
_Value = value;
}
};
void AmbiguousFunc(const Int32 &x) { }
void AmbiguousFunc(const Boolean &x) { }
void NotAmbiguous(__int32 x) { }
void NotAmbiguous(bool x) { }
int main(int argc, char *argv[])
{
AmbiguousFunc(123); // Ambiguous calls to overloaded function
AmbiguousFunc((Int32)123); // works
NotAmbiguous(123);
return 0;
}
发布于 2021-02-24 01:07:49
问题是,给定AmbiguousFunc(123);
,123
可以转换为bool
(标准转换),然后转换为Boolean
(用户定义的转换),这与用户定义的从123
到Int32
的转换排序相同,那么AmbiguousFunc(const Int32 &)
和AmbiguousFunc(const Boolean &)
之间的调用是不明确的。
可以将构造函数更改为模板,并将其限制为只接受适当的类型。
class Boolean
{
private:
bool _Value = false;
public:
// accept bools only; no __int32s
template <typename T, std::enable_if_t<std::is_same_v<T, bool>>* = nullptr>
Boolean(T value)
{
_Value = value;
}
};
class Int32
{
private:
__int32 _Value = 0;
public:
// accept __int32s only; no bools
template <typename T, std::enable_if_t<std::is_same_v<T, __int32>>* = nullptr>
Int32(T value)
{
_Value = value;
}
};
https://stackoverflow.com/questions/66347521
复制