По мотивам эпохального топика "С — зло...
"
http://www.rsdn.ru/forum/cpp.applied/4109801.1.aspxАвтор: LaptevVV
Дата: 10.01.11
struct SchoolInt
{
int i;
operator const int&() const { return i; }
operator int&() { return i; }
// other int operations like ++ etc
struct SIA
{
SchoolInt& h;
const int& x;
mutable bool not_assigned_yet;
template<class U> operator U() const
{
// Looks like you wrote if( a = b ) instead of if( a == b ).
// If you really want to assign inside if-condition, do if( int(a = b) ).
BOOST_STATIC_ASSERT(( ! boost::is_same< U, bool >::value ));
not_assigned_yet=false;
return h.i=x;
}
~SIA() { if (not_assigned_yet) h.i=x; }
};
template<class RHS>
SIA operator=(const RHS& x)
{
// Looks like you wrote int_a = bool_b.
// SchoolInt is strict, please cast explicitly: int_a = (int)bool_b.
BOOST_STATIC_ASSERT(( boost::is_same< RHS, int >::value ));
SIA ret = {*this, x, true};
return ret;
}
};
Проверка:
int main()
{
SchoolInt i = { 5 };
std::cout << i << std::endl;
i = 14; // compiles
std::cout << i << std::endl;
double y = i = 13; // compiles
std::cout << i << " y=" << y << std::endl;
//bool z = int(i = 12); // compiles
bool z = i = 12; // doesn't compile
std::cout << i << " z=" << z << std::endl;
if ( int x = i = 11 ) // compiles
std::cout << i << " x=" << x << std::endl;
//if ( bool w = int(i = 10) ) // compiles
if ( bool w = i = 10 ) // doesn't compile
std::cout << i << " w=" << w << std::endl;
//if ( int(i = 9) ) // compiles
if ( i = 9 ) // doesn't compile
std::cout << i << std::endl;
//if ( int(i = int(!0) ) ) // compiles
if ( i =! 0 ) // doesn't compile
std::cout << i << std::endl;
}
Всех с тяпницей!