C++ 调用唯一_ptr子类的继承模板构造函数
这不是关于模板构造函数,甚至是调用继承的模板构造函数的问题的重复 它特别是关于在unique_ptr模板的类实例(?)的子类中调用继承的构造函数 问题 为了使代码更容易理解,我在本例中使用了C++ 调用唯一_ptr子类的继承模板构造函数,c++,templates,inheritance,constructor,C++,Templates,Inheritance,Constructor,这不是关于模板构造函数,甚至是调用继承的模板构造函数的问题的重复 它特别是关于在unique_ptr模板的类实例(?)的子类中调用继承的构造函数 问题 为了使代码更容易理解,我在本例中使用了using: using B = std::unique_ptr<int *, decltype(&::free)>; class int_ptr : public B { int_ptr(int *b) : B(b, &::free) { }; }; std::uni
using
:
using B = std::unique_ptr<int *, decltype(&::free)>;
class int_ptr : public B {
int_ptr(int *b) : B(b, &::free) { };
};
std::unique
是int
s的智能指针,即int*
的替代品
使用std::unique
时,指针必须是int**
而不是
using B = std::unique_ptr<int *, decltype(&::free)>;
使用B=std::unique\u ptr;
使用
使用B=std::unique\u ptr;
工作代码(谢谢,@CompuChip):。我怀疑您需要使用
使用B=std::unique\u ptr代码>@RSahu这就是答案。很有趣。但仅适用于使用
子句的。我以前用int
替换了int*
的所有实例,但得到:错误:从'int'到'std::unique_ptr::pointer{aka int*}'[-fpermissive]
的转换无效。我想这是因为模板采用类型,但模板实例构造函数采用指针。-谢谢请给我一个答案,这样我就可以把你标记为回答者!证据:。(顺便说一句,您可能希望使该构造函数比private更易于访问。)我没有意识到模板采用类型,但生成的构造函数采用指向同一类型的指针。
void free_int(int* p) {
delete p;
}
template<typename T, void (*D)(T*)>
class unique_dptr : public std::unique_ptr<T, decltype(D)> {
public: unique_dptr(T* t) : std::unique_ptr<T, decltype(D)>(t, D) { };
};
using int_ptr = unique_dptr<int, ::free_int>;
int_ptr i(new int(2));
using B = std::unique_ptr<int *, decltype(&::free)>;
using B = std::unique_ptr<int, decltype(&::free)>;