Beispiellösung

Content

#ifndef UPDATE_HPP
#define UPDATE_HPP

#include <cstdlib>
#include <utility>

namespace update_with_index_impl {

   template<typename F, typename Variable>
   void update(F&& f, std::size_t size, std::size_t index, Variable& var) {
      f(size, index, var);
   }

   template<typename F, typename Variable, typename... Variables>
   void update(F&& f, std::size_t size, std::size_t index,
	 Variable& var, Variables&... vars) {
      f(size, index, var); update(std::move(f), size, index+1, vars...);
   }

} // namespace update_with_index_impl

template<typename F, typename... Variables>
void update_with_index(F&& f, Variables&... vars) {
   update_with_index_impl::update(std::move(f),
      sizeof...(vars), 0, vars...);
}

#endif
#ifndef CSV_READER_HPP
#define CSV_READER_HPP

#include <iostream>
#include <sstream>
#include "update-with-index.hpp"

template<typename... Variables>
bool scan_csv_line(std::istream& in, Variables&... vars) {
   update_with_index([&in](std::size_t size, std::size_t index, auto& var) {
      char delimiter;
      if (index + 1 < size) {
	 delimiter = ',';
      } else {
	 delimiter = '\n';
      }
      std::string s;
      if (std::getline(in, s, delimiter)) {
	 std::istringstream is(s);
	 is >> var;
      }
   }, vars...);
   return !!in;
}

#endif
#include <iostream>
#include <string>
#include "csv-reader.hpp"
#include "csv-printer.hpp"

int main() {
   std::string town;
   unsigned int population;
   unsigned int elevation;
   double area;
   while (scan_csv_line(std::cin, town, population, elevation, area) &&
	 print_csv_line(std::cout, town, population, elevation, area))
      ;
}
#ifndef CSV_PRINTER_HPP
#define CSV_PRINTER_HPP

#include <iostream>
#include <utility>

namespace print_csv_line_impl {

   template<typename Arg>
   bool print_csv_args(std::ostream& out, Arg&& arg) {
      out << "," << arg;
      return !!out;
   }

   template<typename Arg, typename... Args>
   bool print_csv_args(std::ostream& out, Arg&& arg, Args&&... args) {
      return print_csv_args(out, arg) &&
	 print_csv_args(out, std::forward<Args>(args)...);
   }
} // namespace print_csv_line_impl

template<typename Arg, typename... Args>
bool print_csv_line(std::ostream& out, Arg&& arg, Args&&... args) {
   if (out << arg &&
	 print_csv_line_impl::print_csv_args(out,
	    std::forward<Args>(args)...)) {
      out << std::endl;
   }
   return !!out;
}

#endif
theon$ g++ -Wall -o read-cities read-cities.cpp
theon$ ./read-cities 
Freiburg,227590,278,153.06
Heidelberg,159914,114,108.84
Karlsruhe,309999,115,173.46
Konstanz,83789,405,54.11
Mannheim,304781,97,144.96
Stuttgart,628032,247,207.35
Tübingen,88347,341,108.12
Ulm,123953,478,118.69
theon$