Search code examples
c++decltypetype-deduction

Removing CV qualifiers when deducing types using declytype


I have a constant declared as following:

const auto val = someFun();

Now I want another variable with same type of 'val' but without the constant specification.

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

Currently decltype keeps the constness. How to strip it?


Solution

  • From <type_traits>

    You may use in C++14:

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

    or in C++11

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

    Demo