如何使用decltype获取向量元素的类型作为模板参数

时间:2019-04-17 22:07:06

标签: c++ templates decltype argument-deduction

这是我的代码的一部分:

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

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

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

1 个答案:

答案 0 :(得分:2)

  

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

decltype(arr.front())decltype(arr[0])都可以,但是很遗憾,它们都向 const int返回引用考虑到arr是一个常数向量)

例如,您必须删除引用和const

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

使用::value_type更好(IMHO),因为可以避免保持一致性,因此只需要删除引用即可,可以编写

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