首页 > 解决方案 > 如何使用 decltype 获取向量元素的类型作为模板参数

问题描述

这是我的代码的一部分:

int getLength(const vector<int> &arr) {
    auto  n=arr.size(),dis=n;
    unordered_map<int,decltype(dis)> S;
    //...
}

到目前为止,一切都很好。现在,我没有int为 my 硬编码 "" std::unordered_map,而是尝试将其更改为: unordered_map<decltype(arr.front()),decltype(dis)> S; or unordered_map<decltype(arr)::value_type,decltype(dis)> S; or unordered_map<decltype(arr[0]),decltype(dis)> S;

似乎没有一个工作。在这里使用的正确语法是decltype()什么?

标签: c++templatesdecltypetemplate-argument-deduction

解决方案


在这里使用 decltype 的正确语法是什么?

decltype(arr.front())并且decltype(arr[0])都可以,但不幸的是,它们都返回了对const的引用(考虑到这是一个常量向量) intarr

您必须删除引用和常量,例如

std::unordered_map<
      std::remove_const_t<std::remove_reference_t<decltype(arr.front())>>,
      decltype(dis)> S;

使用::value_type更好(恕我直言),因为你避免了常量,所以你必须只删除引用,所以你可以写

   std::unordered_map<
      std::remove_reference_t<decltype(arr)>::value_type,
      decltype(dis)> S;

推荐阅读