Re: Corrected: Proposal: Increasing type safety with a keyword
* Ioannis Vranos:
Proposal:
We can increase type safety in C++ by adding a single keyword. The
current proposal uses the keyword "only".
Example 1:
only int x= 4;
x= 5; // Ok
x= 5.0; // Error
x= 5U // Error
Example 2:
int i= 5;
only unsigned x= 4U;
x= 5; // Error
x= 5LU; // Error
x= i; // Error
Example 3:
only float f= 4.0F;
f= 4; // Error
f= 5.0; // Error
f= 4.0F; // OK
// It accepts any built in type
void somefunc(const int &x);
// It accepts only an int and a const int object
void somefunc(only const int &x);
It is simple like that, and the concept is backwards compatible.
What do you think?
As I recall someone proposed a similar class template a while back.
But even if nobody did, I do that now, so, it's done:
template< typename T >
class Only
{
private:
T myValue;
template< typename U > Only( U v ); // No constr. from other types.
public:
// STATIC_ASSERT( that T is built-in type or something like that )
Only( T v ): myValue( v ) {}
T value() const { return myValue; }
operator T () const { return value(); }
};
Disclaimer: above code is off-the-cuff, not fondled by any dirty compiler.
Hm, thinking of it I have actually proposed something very similar earlier, many
years ago, namely, for the purpose of ensuring 'bool' conditional expressions in
novice code.
However, that proposal was shot down by (1) others' ideas about how unsuitable
this was for novices, and (2) actually trying it, which showed that the
standard's formal UB for redefining a keyword when using standard library
headers, is not just formal UB but, with at least one compiler, very real...
Cheers,
- Alf
--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!