Search code examples
c++typing

How do I specify a parameter type by some quality of the parameter rather than its exact type?


So I have a function in C++ as follows:

void print_vec(std::vector<int> v) {
  for (int i: v) {
    std::cout << i << ' ';
  }
  std::cout << std::endl;
}

Which works and all, but is only applicable to int vectors. I want something like

void print_iter(Iterable<CanDoCout> iterable) {
  for (auto i: iterable) {
    std::cout << i << ' ';
  }
  std::cout << std::endl;
}

How do I implement print_iter? Or how can I find out how to implement generic functions like this?


Solution

  • What you are looking for are templates:

    template <class T>
    void print_iter(const T& iterable) {
      for (const auto& i: iterable) {
        std::cout << i << ' ';
      }
      std::cout << std::endl;
    }
    

    You can go one step further and use concepts or SFINAE to restrict your template to only types that accept the operations you apply.