📜 ⬆️ ⬇️

A short note about patterns and mixing type inference and its explicit assignment

The other day I decided to write my own library for working with FITS files. Yes, I know that there is a CCFITS , but I wanted to invent my bike with ... you know.

One of the possibilities of the format is that data can be written of different types into arrays of different dimensions.
The obvious way to do this is to define something like this:

void setBytePix(int value); void setAxisSize(const std::vector<int> &axis ); 

However, this design is not very convenient. A simple test case:
')
 std::vector srcVector; srcVector.push_back(1024); srcVector.push_back(1024); setAxisSize(srcVector); 

If, instead of std :: vector, there were a QVector from Qt, everything would have looked much nicer.

 setAxisSize(QVector<int>()<<1024<<1024); 

But in the STL there is no such thing, but I would not like to immediately get tied to Qt with all my love for him. The solution was found in this style:

 void setAxeSize(int number, int size); void setNumberDimension(int value); void setAxisDimensionP(int dimensionNumber, int axisSize){ setAxeSize(dimensionNumber, axisSize); } template<typename ...Arguments> void setAxisDimensionP(int dimensionNumber, int axisSize, Arguments... args){ setAxeSize(dimensionNumber, axisSize); ++dimensionNumber; setAxisDimensionP(dimensionNumber, args...); } template<typename ...Arguments> void setAxisSize(Arguments... args) { <s> setNumberDimension(sizeof...(args)/sizeof(int));</s> ( @AxisPod   ) setNumberDimension(sizeof...(args)); setAxisDimensionP(0, args...); } 

Now it is much more convenient:

 setAxisSize(1024, 1024); 

Next came the desire to template and setBytePix. No sooner said than done:

 template <typename T> void setBytePix(){ setBytePix(sizeof(T)*8);} 

Appetite is growing and now I want to call not two functions, but one. Throwing out sad thoughts about crocodiles and modernizing setAxisSize:

 template<typename T, typename ...Arguments> void setAxisSize(Arguments... args) { setBytePix<T>(); setNumberDimension(sizeof...(args)); setAxisDimensionP(0, args...); } 

And now we try:

 setAxisSize<short>(1392,1032); 

Miracle! It is working!
PS MinGW with gcc 4.9.1 was used

Source: https://habr.com/ru/post/216901/


All Articles