gpt4 book ai didi

c++ - 获取可取消引用类型的 value_type

转载 作者:太空狗 更新时间:2023-10-29 20:00:06 27 4
gpt4 key购买 nike

对于任何可取消引用的类型,我将如何实现以下目标?

我发现我当前的解决方案缺乏,因为我需要为我希望它使用的每种类型做一个类模板特化:

template<typename T>
struct get_value_type
{
typedef typename T::value_type value_type;
};

template<typename E>
struct get_value_type<std::unique_ptr<E>>
{
typedef typename E::value_type value_type;
};

template<typename E>
struct get_value_type<std::shared_ptr<E>>
{
typedef typename E::value_type value_type;
};

template<typename E>
struct get_value_type<boost::optional<E>>
{
typedef typename E::value_type value_type;
};

我已经尝试了一些方法,但没有用。

template<typename T, typename IsIndirect = false_type>
get_value_type
{
typedef typename T::value_type value_type;
}

template<typename T>
struct get_value_type<T, true_type>
{
typedef decltype(*boost::declval<E>())::value_type value_type;
};

typedef get_value_type<T, is_indirect<T>::type> value_type;

最佳答案

您正在寻找 std::pointer_traits<PointerType>::element_type住在<memory> .

#include <memory>
#include <boost/optional.hpp>

template <class Ptr>
struct MyPointer
{
};

template <class Ptr>
struct YourPointer
{
typedef signed char element_type;
};

int main()
{
static_assert
(
std::is_same
<
std::pointer_traits<std::unique_ptr<double>>::element_type,
double
>::value,
""
);
static_assert
(
std::is_same
<
std::pointer_traits<std::unique_ptr<short[]>>::element_type,
short
>::value,
""
);
static_assert
(
std::is_same
<
std::pointer_traits<std::shared_ptr<const char>>::element_type,
const char
>::value,
""
);
static_assert
(
std::is_same
<
std::pointer_traits<boost::optional<int*>>::element_type,
int*
>::value,
""
);
static_assert
(
std::is_same
<
std::pointer_traits<MyPointer<long long>>::element_type,
long long
>::value,
""
);
static_assert
(
std::is_same
<
std::pointer_traits<YourPointer<long long>>::element_type,
signed char
>::value,
""
);
}

20.6.3.1 指针特征成员类型[pointer.traits.types]

typedef see below element_type;

Type: Ptr::element_type if such a type exists; otherwise, T if Ptr is a class template instantiation of the form SomePointer<T,
Args>
, where Args is zero or more type arguments; otherwise, the specialization is ill-formed.

哦,还有指针类型的专门化:

template <class T>
struct pointer_traits<T*>
{
typedef T* pointer;
typedef T element_type;
typedef ptrdiff_t difference_type;

template <class U> using rebind = U*;

static pointer pointer_to(see below r) noexcept;
};

关于c++ - 获取可取消引用类型的 value_type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8696452/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com