如何将 std::remove_pointer 与 void* 一起使用? [英] How to use std::remove_pointer with void*?

查看:46
本文介绍了如何将 std::remove_pointer 与 void* 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以这种方式使用 std::unique_ptr:

template <typename Pointer, auto deleter>
using my_unique_ptr = std::unique_ptr<std::remove_pointer<Pointer>, std::integral_constant<decltype(deleter), deleter>>;

它似乎在 Pointer = void* 时工作,但是当尝试在这样的 my_unique_ptr 上使用重置时,我收到此错误:

It seems to work when Pointer = void*, but when trying to use reset on such a my_unique_ptr, I am getting this error:

invalid conversion from 'SampleType' {aka 'void*'} to 'std::unique_ptr<std::remove_pointer<void*>, std::integral_constant<...> >::pointer' {aka 'std::remove_pointer<void*>*'}

不应该 std::remove_pointer* 自动表示 void* 吗?

Shouldn't std::remove_pointer<void*>* automatically mean void*?

推荐答案

您的 my_unique_ptr 不包含 void*.它包含一个 std::remove_pointer*.

Your my_unique_ptr<void*> does not contain void*. It contains a std::remove_pointer<void*>*.

不应该 std::remove_pointer* 自动表示 void* 吗?

Shouldn't std::remove_pointer<void*>* automatically mean void*?

std::remove_pointer 类型并不神奇.这是一种和其他类型一样的类型.这是一个可能的实现:

The std::remove_pointer type is not magic. It's a type like any other. Here's a possible implementation:

template<typename T>
struct remove_pointer {
    using type = T;
};

template<typename T>
struct remove_pointer<T*> {
    using type = T;
};

如您所见,正如您定义的那样,std::unique_ptr 包含指向该结构的指针,就像提到的编译器错误一样.

As you can see, as you defined it, the std::unique_ptr contains a pointer to that struct, just like the compiler error mentionned.

您可能想要做的是使用结构的成员 ::type,也就是 remove_pointer 元函数的结果:

What you probably meant to do is to use the member ::type of the struct, aka the result of the remove_pointer metafunction:

template <typename Pointer, auto deleter>
using my_unique_ptr = std::unique_ptr<typename std::remove_pointer<Pointer>::type, std::integral_constant<decltype(deleter), deleter>>;

在 C++14 中,有一个别名可以简化:

And with C++14, there's a alias to simplify:

template <typename Pointer, auto deleter>
using my_unique_ptr = std::unique_ptr<std::remove_pointer_t<Pointer>, std::integral_constant<decltype(deleter), deleter>>;

这篇关于如何将 std::remove_pointer 与 void* 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆