lundi 29 novembre 2021

How to pass a C++ Template instance to a function?

How can I pass any object of an templated class to another function in C++11?

In the snippet below passInObj does not compile because it complains about Printer&. I want to pass in any Printer it does not matter which template T I have used.

How can I do this and why does the solution below not work?

#include <iostream>
#include <vector>
template <typename T>
class Printer {
  public:
   Printer(const T& tl) : t(tl) {}
   void print() const {
     for (auto x : t) {
        std::cout << x << std::endl;
      }
   }
   const T &t;
};

// THIS LINE DOES NOT COMPILE
void passInObj(const Printer& p) {
   p.print();
}

int main() {
  std::vector<std::string> vec;
  vec.push_back("ABC");
  Printer<std::vector<std::string>> printer(vec);
  printer.print();
  passInObj(p);
  return 0;
}

Aucun commentaire:

Enregistrer un commentaire