svector.hh
Go to the documentation of this file.
1 /* -*- mia-c++ -*-
2  *
3  * This file is part of MIA - a toolbox for medical image analysis
4  * Copyright (c) Leipzig, Madrid 1999-2017 Gert Wollny
5  *
6  * MIA is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with MIA; if not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20 
21 #ifndef mia_core_svector_hh
22 #define mia_core_svector_hh
23 
24 #include <istream>
25 #include <ostream>
26 #include <sstream>
27 #include <vector>
28 #include <stdexcept>
29 
30 #include <mia/core/errormacro.hh>
31 #include <mia/core/typedescr.hh>
32 
34 
39 template <typename T>
40 std::ostream& operator << (std::ostream& os, const std::vector<T>& v) {
41  auto i = v.begin();
42  auto e = v.end();
43 
44  if (i != e)
45  os << *i++;
46  while (i != e)
47  os << "," << *i++;
48  return os;
49 }
50 
51 template <typename T>
53  static bool apply(const std::string& str, T& v){
54  char c;
55  std::istringstream s(str);
56  s >> v;
57  if (s.fail())
58  return false;
59  while (!s.eof() && s.peek() == ' ')
60  s >> c;
61  return s.eof();
62  }
63 };
64 
65 template <>
66 struct __dispatch_translate<std::string> {
67  static bool apply(const std::string& s, std::string& str){
68  str = s;
69  return true;
70  }
71 };
72 
73 
74 template <typename T>
75 std::istream& operator >> (std::istream& is, std::vector<T>& v)
76 {
77  std::vector<T> values;
78  std::string token;
79  T val;
80 
81  while(std::getline(is, token, ',')) {
82  if (__dispatch_translate<T>::apply(token, val))
83  values.push_back(val);
84  else {
85  throw create_exception<std::invalid_argument>("Reading vector: value, '", token,
86  "' could not be translate to ",
87  mia::__type_descr<T>::value);
88  }
89  }
90 
91  if (!v.empty() && v.size() != values.size()) {
92  throw create_exception<std::invalid_argument>("Reading vector: expected ",
93  v.size(), " values, but got ", values.size());
94  }
95  v.swap(values);
96  return is;
97 }
98 
99 
101 
102 #endif
103 
#define NS_MIA_BEGIN
conveniance define to start the mia namespace
Definition: defines.hh:33
std::istream & operator>>(std::istream &is, std::vector< T > &v)
Definition: svector.hh:75
static bool apply(const std::string &str, T &v)
Definition: svector.hh:53
static bool apply(const std::string &s, std::string &str)
Definition: svector.hh:67
#define NS_MIA_END
conveniance define to end the mia namespace
Definition: defines.hh:36