【问题标题】:How to pass a C++ Template instance to a function?如何将 C++ 模板实例传递给函数?
【发布时间】:2021-11-29 16:07:00
【问题描述】:

如何将模板化类的任何对象传递给 C++11 中的另一个函数?

passInObj 下面的sn-p 中没有编译,因为它抱怨Printer&。我想传入任何Printer,不管我使用的是哪个模板T

我该怎么做?为什么下面的解决方案不起作用?

#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;
}

【问题讨论】:

    标签: c++ c++11 generics


    【解决方案1】:

    我该怎么做

    你需要把它做成函数模板:

    template <class T>
    void passInObj(const Printer<T>& p) {
        p.print();
    }
    

    Demo

    为什么下面的解决方案不起作用?

    因为Printer 不是类型,它只是一个模板。要使passInObj 与任何Printer&lt;T&gt; 一起工作,您需要将该函数制作成函数模板,以便为每个用于调用它的Printer&lt;T&gt; 实例化它。

    【讨论】:

      【解决方案2】:

      虽然@TedLyngmo 的答案应该是您的默认答案,但如果您出于某种原因无法将passInObj() 设为模板,您也可以通过多态接口执行此操作。

      这是通过添加将由所有Printer&lt;&gt; 类派生的基接口类来完成的:

      #include <iostream>
      #include <vector>
      
      class IPrinter {
        public:
          virtual void print() const = 0;
      
        // Either that or public and virtual
        protected:
          ~IPrinter() = default;
      };
      
      template <typename T>
      class Printer : public IPrinter {
        public:
         Printer(const T& tl) : t(tl) {}
         void print() const override {
           for (auto x : t) {
              std::cout << x << std::endl;
            }
         }
         const T &t;
      };
      
      void passInObj(const IPrinter& 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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-01
        • 2014-03-11
        相关资源
        最近更新 更多