GMan has posted a code for the delicious auto_cast
“operator” that allows to write code such as the following in C++:
float f = 4.0f;
int i = auto_cast(f);
// instead of:
int j = static_cast<int>(f);
or, more saliently,
T x = value;
typename nested_type<with, template_arguments>::type y = auto_cast(x);
// instead of
typedef typename nested_type<with, template_arguments>::type my_type;
my_type z = static_cast<my_type>(x);
Basically, the operator is great in removing unnecessary redundancy from a static_cast
, and at the same time is still safe. It’s even more safe than static_cast
since it prevents accidentally mismatching the types:
int i = 1234;
short s = static_cast<char>(i); // s == -46, not 1234!
However, j_random_hacker has noticed a flaw in the operator:
static_cast allows downcasts, which are potentially unsafe.
Indeed, an auto_cast
should probably forbid downcasts because they may fail:
class base { };
class derived : public base { };
base b;
derived* pd = auto_cast(&b); // should fail at compile time.
Hence my question:
How would you modify the auto_cast
implementation in order to forbid downcasts?
This will probably involve enable_if
. I’m especially interested in a solution that allows the compiler to provide good diagnostics in case of failure (= readable error messages).