Making auto_cast safe

前端 未结 3 506
长情又很酷
长情又很酷 2021-02-05 19:09

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);
// in         


        
3条回答
  •  执笔经年
    2021-02-05 19:41

    I wouldn't even use auto_cast because static_cast, const_cast, dynamic_cast and reinterpret_cast are also made ugly by design to help pointing code that could need refactoring : a ugly operation should have an ugly look.

    A secondary reason for introducing the new-style cast was that C-style casts are very hard to spot in a program. For example, you can't conveniently search for casts using an ordinary editor or word processor. This near-invisibility of C-style casts is especially unfortunate because they are so potentially damaging. An ugly operation should have an ugly syntactic form. That observation was part of the reason for choosing the syntax for the new-style casts. A further reason was for the new-style casts to match the template notation, so that programmers can write their own casts, especially run-time checked casts.

    http://www2.research.att.com/~bs/bs_faq2.html#static-cast

    I prefer to see clearly in the code where it could be better, or where we explicitely need to make this ugly operation.

提交回复
热议问题