我最近一直在进行大规模的重构,我正在更改很多代码以返回布尔值而不是显式的返回代码。为了帮助这种重构,我决定尽可能依靠编译器,让它告诉我需要更改代码的地方。我通过引入以下类来做到这一点(有关其工作原理的详细信息,请参见此处):
///
/// Typesafe boolean class
///
class TypesafeBool
{
private:
bool m_bValue;
struct Bool_ {
int m_nValue;
};
typedef int Bool_::* bool_;
inline bool_ True() const { return &Bool_::m_nValue; }
inline bool_ False() const { return 0; }
public:
TypesafeBool( const bool bValue ) : m_bValue( bValue ){}
operator bool_() const { return m_bValue ? True() : False(); }
};
现在,我没有使用普通bool
类型作为返回类型,而是使用了这个类,这意味着我不能再编译这样的东西了:
TypesafeBool SomeFunction();
long result = SomeFunction(); // error
太好了:它让编译器为我完成了很多艰苦的工作,从而使重构在庞大的代码库上变得易于管理。所以现在我已经完成了重构,我很想继续使用这个类并继续使用它,因为它为我们提供了内置bool
类型所没有的额外安全级别。
然而,有一个“问题”阻止我这样做。目前我们在代码中大量使用了三元运算符,问题是它与这个没有显式强制转换的新类不兼容:
TypesafeBool result = ( 1 == 2 ? SomeFunction() : false ); // error: different types used
TypesafeBool result = ( 1 == 2 ? SomeFunction() : (TypesafeBool)false );
如果我可以“解决”这个问题,以便我可以无缝地使用我的课程,我可能会在整个代码库中继续使用它。有谁知道这个问题的解决方案?或者只是不可能做我想做的事?