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-2015 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 
35 template <typename T>
36 std::ostream& operator << (std::ostream& os, const std::vector<T>& v)
37 {
38  for(auto x: v)
39  os << x << ",";
40  return os;
41 }
42 
43 template <typename T>
45  static bool apply(const std::string& str, T& v){
46  char c;
47  std::istringstream s(str);
48  s >> v;
49  while (!s.eof() && s.peek() == ' ')
50  s >> c;
51  return s.eof();
52  }
53 };
54 
55 template <>
56 struct __dispatch_translate<std::string> {
57  static bool apply(const std::string& s, std::string& str){
58  str = s;
59  return true;
60  }
61 };
62 
63 
64 template <typename T>
65 std::istream& operator >> (std::istream& is, std::vector<T>& v)
66 {
67  std::vector<T> values;
68  std::string token;
69  T val;
70 
71  while(std::getline(is, token, ',')) {
72  if (__dispatch_translate<T>::apply(token, val))
73  values.push_back(val);
74  else {
75  throw create_exception<std::invalid_argument>("Reading vector: value, '", token,
76  "' could not be translate to ",
77  mia::__type_descr<T>::value);
78  }
79  }
80 
81  if (!v.empty() && v.size() != values.size()) {
82  throw create_exception<std::invalid_argument>("Reading vector: expected ",
83  v.size(), " values, but got ", values.size());
84  }
85  v.swap(values);
86  return is;
87 }
88 
89 
91 
92 #endif
93 
#define NS_MIA_BEGIN
conveniance define to start the mia namespace
Definition: defines.hh:43
std::istream & operator>>(std::istream &is, std::vector< T > &v)
Definition: svector.hh:65
static bool apply(const std::string &str, T &v)
Definition: svector.hh:45
static bool apply(const std::string &s, std::string &str)
Definition: svector.hh:57
#define NS_MIA_END
conveniance define to end the mia namespace
Definition: defines.hh:46