0
這個習語幫助我解決了幾個問題,但我不知道這是如何被稱爲的,谷歌搜索沒有幫助。其目的是將不同的模板類存儲在異構集合中,一個衆所周知的示例用法是std::any
。C++ - 一個習語的術語
class TemplateBase
{
public:
virtual void f() = 0;
virtual ~TemplateBase() {}
};
template<typename T>
class TemplateImplementation : public TemplateBase
{
T data;
public:
virtual void f() override
{
// some T-specific implementation
std::cout << data << std::endl;
}
};
std::vector<std::unique_ptr<TemplateBase>> collection;
collection.emplace_back(new TemplateImplementation<int>{1});
collection.emplace_back(new TemplateImplementation<std::string>{"hello"});
「類型擦除」是您正在尋找的術語。 – GManNickG
的確,遺漏了遺產。固定OP,對不起。 – dobragab
http://stackoverflow.com/documentation/c%2b%2b/2872/type-erasure – Brian