struct Delete
{
template <typename T>
void operator() (T* t)
{
delete t;
}
};
template <typename Container>
class SmartContainer
: public Container
{
public:
~SmartContainer()
{
std::for_each(Container::begin(), Container::end(), Delete());
}
SmartContainer(const SmartContainer& other)
{
for (typename Container::const_iterator iter = other.begin(); iter != other.end(); ++iter) {
push_back(new typename Container::value_type(**iter));
}
}
SmartContainer() {}
};
在这段代码中,我尝试实现了一个智能容器。容器包含指针。它会在销毁时删除指针。问题在于编写复制构造函数。它应该复制对象并将副本的指针放在容器中。我在这个push_back
行中收到错误,因为Container::value_type
是指针类型,但它需要创建一个解除引用类型的对象。 std::remove_pointer
在这里可能很有用,但我的编译器不支持c ++ 11。也许带有智能指针的普通容器是更好的选择,但我需要解决方案。
答案 0 :(得分:3)
您可以实施自己的remove_pointer
(来自cppreference.com):
template< class T > struct remove_pointer {typedef T type;};
template< class T > struct remove_pointer<T*> {typedef T type;};
template< class T > struct remove_pointer<T* const> {typedef T type;};
template< class T > struct remove_pointer<T* volatile> {typedef T type;};
template< class T > struct remove_pointer<T* const volatile> {typedef T type;};
然后执行typename remove_pointer<Container::value_type>::type
。
答案 1 :(得分:1)
更改模板参数。而不是Container
使它成为Container<T*>
,那么您将拥有可用的基础对象类型。
template <typename Container, typename T>
class SmartContainer
: public Container<T*>