使用 [] 运算符从指向 std::array<T, N> 的指针获取类型?

Get the type from a pointer to std::array<T, N> using the [] operator?

本文关键字:gt 指针 取类型 获取 std lt 使用 array 运算符      更新时间:2023-10-16

我的代码中有一个类似于std::array<T1, N>的类和一个函数:

template <class T2>
inline void f(T2* const myarray)
{
    std::pair<double, /*SOMETHING*/> x;
}

假设T2*是指向我的类的指针,与std::array<T1, N>相比,我想知道我必须写什么而不是/*SOMETHING*/才能从myarray[]操作符中获得T1 ?

注意:我不要求更聪明的方法从指向std::array的指针获取类型

这个适合我:

#include <type_traits>
#include <array>
#include <utility>
template <class T2>
inline void f(T2* const myarray)
{
    std::pair<double, typename T2::value_type> x;
    static_assert(std::is_same<decltype(x.second), int>::value, "");
}
int
main()
{
    std::array<int, 2> a;
    f(&a);
}

如果你的"类数组"类模板没有value_type,下面的代码也可以工作:

std::pair<double, typename std::remove_reference<decltype((*myarray)[0])>::type> x;

但仅供参考,通常不使用const限定形参,并且在c++ 11中,如果您碰巧返回形参(如),甚至会导致悲观:

return myarray;

虽然在本例中myarray是一个指针,但在本例中它是否为const并不重要

如果你的意思是:

inline void f(T2 const* myarray)

(指向const T2,而不是指向T2const指针)

那么上面的配方需要稍微调整一下:

std::pair<double, typename std::remove_const<
                                   typename std::remove_reference<
                                      decltype((*myarray)[0])
                                   >::type
                                >::type> x;

如果你的"类数组"类模板确实有value_type,那么第一个建议:

std::pair<double, typename T2::value_type> x;

不管const在哪里