ゆとりーなの日記

日記的な事を書いて行くと思はれる

モダンscanf!?

ダンなscanf?を書いてみました。

#include <iostream>
#include <string>
#include <tuple>

struct input_data {
  template <typename T>
  void operator ()(T &t) const {
    std::cin >> t;
  }
};

template <typename Tuple, typename Func, std::size_t N = std::tuple_size<Tuple>::value - 1>
struct for_each_impl {
  static void pred(Tuple &tup, const Func func) {
    func(std::get<std::tuple_size<Tuple>::value - N - 1>(tup));
    for_each_impl<Tuple, Func, N - 1>::pred(tup, func);
  }
};

template <typename Tuple, typename Func>
struct for_each_impl<Tuple, Func, 0> {
  static void pred(Tuple &tup, const Func func) {
    func(std::get<std::tuple_size<Tuple>::value - 1>(tup));
  }
};

template <typename Tuple, typename Func>
void for_each(Tuple &tup, const Func func) {
  for_each_impl<Tuple, Func>::pred(tup, func);
}

template <typename ... Types>
std::tuple<Types ...> scanf() {
  std::tuple<Types ...> temp;
  for_each(temp, input_data());
  return temp;
};

int main() {
  const auto in = scanf<int, double, std::string>();
  std::cout << std::get<0>(in) << "," << std::get<1>(in) << "," << std::get<2>(in) << std::endl;
  return 0;
}

普段は窓ばっかり相手にしてるので使い勝手とかは知りません。