Search code examples
c++decltype

Shorten std::remove_const(decltype(something)) via "using" expression


If I use C way, I can do following:

#define NOCONST(x) std::remove_const<decltype(x)>::type
const int a;
NOCONST(a) b;

If I use C++ way

template <typename T>
using noConst = std::remove_const<T>::type;
const int a;
noConst<decltype(a)> b;

Despite, that "using" is more correct, macro is shorter. Is there any way to further shorten "using" expression? without additional decltype in template parameter?

To clarify - I need use something like

noConst(a) b;

or

noConst<a> b;

without decltypes and other stuff in params. decltype shoulde be somehow moved to "using" expression, but I have no idea how or if is this possible overall.


Solution

  • I don't think this is possible. Especially in the form you are requiring. It may be possible to use type deduction in function contexts like this:

    template<typename Type>
    auto no_const(Type&&) { return typename std::decay<Type>::type(); }
    

    but that would yield a syntax like this:

    auto x = no_const(a);
    

    Live demo

    Diclamer: the use of std::decay in the implementation may yield weird results with arrays and other "special" types; I haven't tested it; this is just a prototype.

    I have to say that I highly discourage its use as it's really non-idiomatic C++. Just type those extra characters and use decltype in the object declaration.