智能指针的概念
给定一个这样的类模板:
template<typename T>
struct foo
{
T data;
};
如何确定是否T是智能指针,例如std::shared_ptr<T_underlying>使用 C++20 概念?
我想foo<T>根据这个标准添加功能。例如,我想使用新概念系统,而不是使用 SFINAE。
我想实现这样的目标:
template<typename T>
struct foo
{
T data;
void func()
requires is_shared_ptr_v<T>
{
// ...
}
};
STL 中是否存在相关概念?如果没有,我假设我可以写一个概念 for std::shared_ptr, one forstd::unique_ptr等等,然后将它们与逻辑或一般is_smart_pointer概念联系在一起?
回答
您可能首先创建一个特征来检测类型是否是 a 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;