[英]How to pass a C++ Template instance to a function?
如何將模板化 class 的任何 object 傳遞給 Z657433F6E7DAA506474F8181 中的另一個function ?
在下面的代碼片段中passInObj
沒有編譯,因為它抱怨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;
}
我怎樣才能做到這一點
您需要將其制作成 function 模板:
template <class T>
void passInObj(const Printer<T>& p) {
p.print();
}
為什么下面的解決方案不起作用?
因為Printer
不是一種類型,它只是一個模板。 要使passInObj
與任何Printer<T>
一起使用,您需要將 function 制作成 function 模板,以便為每個用於調用它的Printer<T>
實例化它。
雖然默認情況下@TedLyngmo 的答案應該是您的首選,但如果由於某種原因無法將passInObj()
模板,您也可以通過多態接口執行此操作。
這是通過添加將由所有Printer<>
類派生的基本接口 class 來完成的:
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.