c++ - 通过类型的变量键入特征

标签 c++

我想测试一个变量类型的属性。我可以,但是代码太冗长了。

考虑一个示例,其中我定义了一个与容器中的值类型相同类型的变量:

#include <vector>

int main() {
  std::vector<int> v, &rv=v;

  // ‘rv’ is not a class, namespace, or enumeration
  //rv::value_type i1;

  // Ok
  decltype(v)::value_type i2;

  // decltype evaluates to ‘std::vector<int>&’, which is not a class or enumeration type
  //decltype(rv)::value_type i3;

  // Ok
  std::remove_reference<decltype(rv)>::type::value_type i4;
}

我可以接受 decltype,但是添加 std::remove_reference 太多了。在不定义辅助模板的情况下,有没有什么好的方法可以缩短代码?

最佳答案

你可以用其中之一来缩短它

std::decay_t<decltype(rv)>::value_type i4 = 42;

std::decay_t<decltype(*std::begin(rv))> i4 = 42;

关于c++ - 通过类型的变量键入特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39458660/

相关文章:

c++ - 在 python 中嗅探音频?

c++ - std::string {又名 std::basic_string<char> }' to ' char*' 赋值|

c++ - typedef 函数不是类型名?

C++ 棘手的 Const 引用考试任务?

python - 从 Python 调用 C++ dll

c++ - gdb 列表错误 "No such file or directory"

c++ - 设置 Promise 豁免会导致中止调用

c++ -/clr MFC Application中的异常处理(用/EHa编译)

c++ - 嵌入式 C++ : to use STL or not?

c++ - 将日期转换为 const char*