[cctbxbb] Idiot C++ question

Luc Bourhis luc_j_bourhis at mac.com
Tue May 15 04:41:49 PDT 2012


> 
> I can see that problem with pointers but it doesn't seem to apply to double [...]

You are perfectly right and I do prefer double(i) as well as it is less noisy. In template class or function, where a template parameter T will end up being a floating point type, you will see T(0) or T(1) a lot in the cctbx corpus, as a way to denote those constant in a way that is generic e.g. ("0." or "1." would not do as those denotes double and this may not work when instantiating the template for T=float).

Too many people have been brainwash by the diktat: "you shall always use static_cast"!

In any case, as I stated in my short answer, it is a matter of taste whether you write static_cast<T>(obj), (T)obj or T(obj) when T is not a pointer, and stylistic issues are only very loosely enforced among cctbx developers. What matters is that the compiler will actually prevent mistakes: consider my example again but let's do the conversion without the pointers:

  bar y = (bar)x;

My compiler fails with the following error messages

conv.cpp:15:11: error: no matching conversion for C-style cast from 'foo' to 'bar'
  bar y = (bar)x;
          ^~~~~~
conv.cpp:8:8: note: candidate constructor (the implicit copy constructor) not viable: no known
      conversion from 'foo' to 'const bar' for 1st argument;
struct bar { 
       ^
conv.cpp:10:3: note: candidate constructor not viable: no known conversion from 'foo' to 'double' for
      1st argument;
  bar(double d): d(d) {} 

which tells you the whole story!

Luc
 


More information about the cctbxbb mailing list