2013-10-27 20 views
0

快速的问题,当我有一些静态的多态类如何在static polymophism中声明基类的std :: list?

template <class Derived> 
struct base 
{ 
} 

struct derived1 : public base<derived1>{ 
} 

//do the same for derived2, derived3. 

如何声明一个std ::列表将包含很多derived1 derive2 derived3的对象?像std :: list < base>?我想不是,对吧?

PS:显然派生类将在运行时被选中,我需要在运行时访问派生类的功能。

非常感谢!

回答

0

由于您使用CRTP,你需要定义一个共同的基类为您base类模板的所有实例:

class base_base { public: virtual ~base_base() = default; }; 
template<typename T> class base : public base_base; 

其次,你需要额外的间接,所以你必须使用std::unique_ptr

template<typename T, typename... Args> 
std::unique_ptr<T> make_unique(Args&&... args) { 
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); 
} 

std::list<std::unique_ptr<base>> my_list; 
my_list.emplace_back(make_unique<derived1>()); 
my_list.emplace_back(make_unique<derived2>()); 
my_list.emplace_back(make_unique<derived3>()); 

在C++ 14你最有可能可以使用std::make_unique,这样你就不必自己定义的功能。

+0

谢谢。可以解释一下为什么我们必须在这里使用unique_ptr?为什么我不能简单地使用boost :: shared_ptr?谢谢! –

+0

@ccfenix'boost :: shared_ptr'应该可以正常工作,但不太可能需要共享所有权。 – rightfold

+0

@Elyse我也很好奇为什么你想要一个make_unique,以及为什么你定义一个静态多态性的虚拟方法..? – TomSmartBishop