【发布时间】:2015-10-29 15:13:43
【问题描述】:
这不是模板构造函数甚至调用继承的模板构造函数的问题的重复。
它专门用于在 unique_ptr<...> 模板的类实例(?)的子类中调用继承的构造函数。
问题
为了让代码更容易理解,我在这个例子中使用了using:
using B = std::unique_ptr<int *, decltype(&::free)>;
class int_ptr : public B {
int_ptr(int *b) : B(b, &::free) { };
};
但编译失败:
In constructor 'int_ptr::int_ptr(int*)':
error: no matching function for call to
'std::unique_ptr<int*, void (*)(void*) throw ()>::unique_ptr(int*&, void (*)(void*) throw ())'
int_ptr(int *b) : B(b, &::free) { };
^
我能想到的缺少功能匹配的唯一可能原因是存在throw (),但我不确定该怎么做,或者它是否是个问题。可能unique_ptr 是禁止抛出的。
否则,不匹配的函数正是我期望匹配的。
原因
我不想在每次声明 unique_ptr 的实例时都指定析构函数。这个答案https://stackoverflow.com/a/16615285/2332068 有一个很好的选择,但我很想知道我的尝试有什么问题。
当然,在现实生活中它不是int*,我试图用unique_ptr 包装,而是一些不透明的(但不是void*)指针。
我的意图是在范围退出时正确释放来自 C API 的所有这些指针。
也许我可以使用析构函数将这些指针约束到一个类/结构中,但我看不出它会节省多少。
结果
根据@RSahu 的提示,我想出了unique_dptr 来避免需要继续指定析构函数,但可以替代在std 命名空间中覆盖模板删除函数:
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)>;。 -
@RSahu 这就是答案。
-
有趣。但仅适用于
using子句。我之前已经将int*的所有实例替换为int,但得到:error: invalid conversion from 'int' to 'std::unique_ptr<int, void (*)(void*) throw ()>::pointer {aka int*}' [-fpermissive]我猜这是因为模板采用类型,但模板实例构造函数采用指针。 - 谢谢!请将其作为答案,以便我将您标记为回答者!
标签: c++ templates inheritance constructor