通过"using"表达式缩短 std::remove_const(decltype(something))

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

本文关键字:const using something decltype remove std 通过 表达式      更新时间:2023-10-16

如果我使用C方式,我可以执行以下操作:

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

如果我使用C++方式

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

尽管如此,"使用"更正确,宏更短。有没有什么方法可以进一步缩短"正在使用"的表达?模板参数中没有额外的decltype?

为了澄清-我需要使用类似的东西

noConst(a) b;

noConst<a> b;

在params中没有decltypes和其他东西。decltype应该以某种方式被移到"using"表达式,但我不知道这是如何或是否可能的。

我认为这是不可能的。尤其是在你需要的形式上。可以在函数上下文中使用类型推导,如

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

但这会产生这样的语法:

auto x = no_const(a);

现场演示

Diclamer:在实现中使用std::decay可能会对数组和其他"特殊"类型产生奇怪的结果;我还没有测试过;这只是一个原型。

我不得不说,我强烈反对使用它,因为它确实是不地道的C++。只需键入这些额外的字符并在对象声明中使用decltype