SignalTypeConverter.h
Go to the documentation of this file.
1 // SignalTypeConverter.h
2 //
3 // David Adams
4 // November 2015
5 //
6 // Utility class to convert between int and floating point types.
7 // Float to int conversion is rounding to nearest int:
8 // (-1.5 , 0.5] --> -1
9 // (-0.5 , 0.5) --> 0
10 // [ 0.5 , 1.5) --> 1
11 //
12 // Future development may add parameters which specify different
13 // conversion strategies.
14 //
15 // Examples of usage.
16 // float val = 1.2;
17 // SignalTypeConverter sigcon.
18 // int ival1 = sigcon.floatToInt(val);
19 // short ival2 = sigcon.convert<short>(val);
20 
21 #include <type_traits>
22 
24 
25 public:
26 
27  // Ctor.
29 
30  // Convert type T1 to type T2.
31  // Uses floatToInt if If T1 is floating and T2 is integral.
32  // Otherwise, standard type conversion.
33  // Usage: int ival = convert<int>(myfloat);
34  template<typename T2, typename T1>
35  T2 convert(T1 val) const {
36  if ( std::is_floating_point<T1>() && std::is_integral<T2>() ) {
37  return floatToInt<T2, T1>(val);
38  } else {
39  return T2(val);
40  }
41  }
42 
43  // Conversion from floating point to int with arbitrary types.
44  template<typename INT =int, typename FLOAT>
45  INT floatToInt(FLOAT val) const {
46  if ( val < 0.0 ) return -floatToInt<INT, FLOAT>(-val);
47  return INT(val + 0.5);
48  }
49 
50 };
INT floatToInt(FLOAT val) const
Definition: 013_class.h:14
T2 convert(T1 val) const
Definition: 013_class.h:10