libvisiontransfer  10.6.0
conversionhelpers.h
1 /*******************************************************************************
2  * Copyright (c) 2023 Allied Vision Technologies GmbH
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a copy
5  * of this software and associated documentation files (the "Software"), to deal
6  * in the Software without restriction, including without limitation the rights
7  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8  * copies of the Software, and to permit persons to whom the Software is
9  * furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *******************************************************************************/
14 
15 namespace visiontransfer {
16 namespace internal {
17 
19 class VT_EXPORT ConversionHelpers {
20 public:
22  template<typename T>
23  static double anyToDouble(T val);
24 
26  template<typename T>
27  static std::string anyToString(T val) {
28  std::ostringstream ss;
29  ss << std::setprecision(std::numeric_limits<double>::max_digits10 - 1) << val;
30  return ss.str();
31  }
32 
33  // Wrap anything in to_string if string is expected, or cast for numbers
34  template<typename S, typename T, typename std::enable_if<std::is_arithmetic<S>::value>::type* = nullptr >
35  static S toStringIfStringExpected(T val) {
36  return static_cast<S>(val);
37  }
38  template<typename S, typename T, typename std::enable_if<std::is_same<S, std::string>::value>::type* = nullptr >
39  static S toStringIfStringExpected(T val) {
40  return std::to_string(val);
41  }
42 };
43 
44 template<> inline double ConversionHelpers::anyToDouble(const std::string& val) { return atol(val.c_str()); }
45 template<> inline double ConversionHelpers::anyToDouble(std::string val) { return atol(val.c_str()); }
46 template<> inline double ConversionHelpers::anyToDouble(const char* val) { return atol(val); }
47 template<typename T> inline double ConversionHelpers::anyToDouble(T val) { return (double)val; }
48 
49 } // namespace internal
50 } // namespace visiontransfer
static double anyToDouble(T val)
Converts any type to a double.
Internal helper functions for type conversion.
static std::string anyToString(T val)
Converts any type to a string.
Allied Vision