c++ - 使用 declytype 推导类型时删除 CV 限定符

标签 c++ decltype type-deduction

我有一个常量声明如下:

const auto val = someFun();

现在我想要另一个具有相同类型“val”但没有常量规范的变量。

decltype(val) nonConstVal = someOtherFun();
// Modify nonConstVal, this is error when using decltype

当前 decltype 保持常量。怎么剥掉呢?

最佳答案

来自 <type_traits>

您可以在 C++14 中使用:

std::remove_cv_t<decltype(val)> nonConstVal = someOtherFun();

或在 C++11 中

std::remove_cv<decltype(val)>::type nonConstVal = someOtherFun();

Demo

关于c++ - 使用 declytype 推导类型时删除 CV 限定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32307342/

相关文章:

c++11 - 使用 GCC 在继承的模板静态成员函数上使用 decltype

c++ - 使用模板模板参数时模板参数推导失败

c++ - C++11 标准是否通过 "n2 is int&"保证 "auto n2 = const_cast<int&>(n);"?

c++ - 模板引用的类型推导

C++通用模板化类算术

c++ - c++:struct和decltype比较器的priority_queue

c++ - 在 C++ 中检测不安全的 const 引用绑定(bind)

c++ - std::string 不是 std::vector<char> 吗?

C++ 将参数传递给内联汇编函数

C++:使用堆栈反转文本文件中的行