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

Removing CV qualifiers when deducing types using declytype

我有一个常量声明如下:

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