2017-03-16 51 views
0

這個習語幫助我解決了幾個問題,但我不知道這是如何被稱爲的,谷歌搜索沒有幫助。其目的是將不同的模板類存儲在異構集合中,一個衆所周知的示例用法是std::anyC++ - 一個習語的術語

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"}); 
+4

「類型擦除」是您正在尋找的術語。 – GManNickG

+0

的確,遺漏了遺產。固定OP,對不起。 – dobragab

+0

http://stackoverflow.com/documentation/c%2b%2b/2872/type-erasure – Brian

回答