将常量添加到引用

Add const to reference

本文关键字:引用 添加 常量      更新时间:2023-10-16

我想通过typedef const A B;将 const 添加到引用类型中。

不知何故它不起作用。这在 c++ 中是不可能的吗?

测试:

#include <type_traits>
typedef int& A;
typedef const A B;  // <-- Add const
// typedef std::add_const<A>::type B;  // also doesn't work.
static_assert(std::is_const<typename std::remove_reference<
B>::type>::value, "is const");
int main() {
return 0;
}

编译错误:

add2.cpp:5:1: error: static assertion failed: is const
static_assert(std::is_const<typename std::remove_reference<
^~~~~~~~~~~~~

不知何故它不起作用。这在 c++ 中是不可能的吗?

不是你做事的方式。typedef不像预处理器宏那样工作。

typedef int& A;
typedef const A B;

不转换为

typedef int& A;
typedef const int& B;

const

typedef const A B;

适用于A,而不是Aint部分。由于引用在C++中是不可变的,因此const A与从文字点视图A相同。


您可以使用:

typedef int const& B;

如果你想从A派生它,你可以使用:

using B = typename std::remove_reference<A>::type const&;

如果您能够使用 C++14 或更高版本,则可以将其简化为:

using B = std::remove_reference_t<A> const&;

不幸的是,std::add_const<T>并没有按照你的想法做参考。 将const添加到引用的方法是:

using in_type = double&;
using out_type = std::add_lvalue_reference_t<std::add_const_t<std::remove_reference_t<in_type>>>;
static_assert( std::is_same<out_type, double const&>{} , "!");

我再次被这个咬了一口,一年后找到了自己的答案。 甚至想:)投票。

这更笼统,更简洁,但仍然不完美。

using in_type = Ref;
using out_type = decltype( std::as_const(std::declval<in_type>()));