使用 [] 运算符从指向 std::array<T, N> 的指针获取类型?
Get the type from a pointer to std::array<T, N> using the [] operator?
我的代码中有一个类似于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
,而不是指向T2
的const
指针)
那么上面的配方需要稍微调整一下:
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
在哪里
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- ``这个''不能用this-&gt;指针变量