智能指针的概念
Concept for smart pointers
给定这样一个 class 模板:
template<typename T>
struct foo
{
T data;
};
如何使用C++20概念判断T
是否是智能指针,如std::shared_ptr<T_underlying>
?
我想根据此标准向 foo<T>
添加功能。例如,我不想使用SFINAE,而是想使用新概念系统。
我想实现这样的目标:
template<typename T>
struct foo
{
T data;
void func()
requires is_shared_ptr_v<T>
{
// ...
}
};
STL 中是否存在这方面的概念?如果没有,我假设我可以为 std::shared_ptr
、std::unique_ptr
等写一个概念,然后将它们与逻辑或一般的 is_smart_pointer
概念联系在一起?
您可能首先创建一个特征来检测类型是否为 std::shared_ptr
(方法取决于您是否要考虑继承)。
然后利用特征建立概念:
template <typename T> struct is_shared_ptr : std::false_type {};
template <typename T> struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
template <typename T> concept IsSharedPtr = is_shared_ptr<T>::value;
或
template <typename T>
std::true_type inherit_from_shared_ptr_impl(const std::shared_ptr<T>*);
std::false_type inherit_from_shared_ptr_impl(...);
template <typename T>
using inherit_from_shared_ptr =
decltype(inherit_from_shared_ptr_impl(std::declval<T*>()));
template <typename T> concept InheritFromSharedPtr = inherit_from_shared_ptr<T>::value;
写“类似于指针”。具有一元取消引用,显式转换为 bool,并且是指针或具有运算符箭头。也许(对于非指针)得到 returns 与运算符箭头相同的类型。
然后声明智能指针是类似于指针的东西,但不是指针。
请注意,某些迭代器是此规则下的智能指针。
如果你想要一个“拥有”指针,你必须有一个手动特征;除了语义之外,没有其他方法可以说明这一点。
给定这样一个 class 模板:
template<typename T>
struct foo
{
T data;
};
如何使用C++20概念判断T
是否是智能指针,如std::shared_ptr<T_underlying>
?
我想根据此标准向 foo<T>
添加功能。例如,我不想使用SFINAE,而是想使用新概念系统。
我想实现这样的目标:
template<typename T>
struct foo
{
T data;
void func()
requires is_shared_ptr_v<T>
{
// ...
}
};
STL 中是否存在这方面的概念?如果没有,我假设我可以为 std::shared_ptr
、std::unique_ptr
等写一个概念,然后将它们与逻辑或一般的 is_smart_pointer
概念联系在一起?
您可能首先创建一个特征来检测类型是否为 std::shared_ptr
(方法取决于您是否要考虑继承)。
然后利用特征建立概念:
template <typename T> struct is_shared_ptr : std::false_type {};
template <typename T> struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
template <typename T> concept IsSharedPtr = is_shared_ptr<T>::value;
或
template <typename T>
std::true_type inherit_from_shared_ptr_impl(const std::shared_ptr<T>*);
std::false_type inherit_from_shared_ptr_impl(...);
template <typename T>
using inherit_from_shared_ptr =
decltype(inherit_from_shared_ptr_impl(std::declval<T*>()));
template <typename T> concept InheritFromSharedPtr = inherit_from_shared_ptr<T>::value;
写“类似于指针”。具有一元取消引用,显式转换为 bool,并且是指针或具有运算符箭头。也许(对于非指针)得到 returns 与运算符箭头相同的类型。
然后声明智能指针是类似于指针的东西,但不是指针。
请注意,某些迭代器是此规则下的智能指针。
如果你想要一个“拥有”指针,你必须有一个手动特征;除了语义之外,没有其他方法可以说明这一点。