将const添加到引用

编程入门 行业动态 更新时间:2024-10-28 20:24:01
本文介绍了将const添加到引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I want to add const to a reference type by typedef const A B;.

工作。

测试:

#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 ++中是不可能的吗?

Somehow it doesn't work. Is this not possible in c++?

不符合您的方式 typedef 不能像预处理器宏一样工作。

Not with the way you are doing it. typedef does not work like pre-processor macros.

typedef int& A; typedef const A B;

不翻译为

typedef int& A; typedef const int& B;

typedef const A B;

应用于 A ,而不是 A 的 int 部分。由于引用在C ++中是不可变的,因此 const A 与 A 从类型点视图。

applies to A, not the int part of A. Since references are immutable in C++, const A is the same as A from a type point view.

您可以使用:

typedef int const& B;

如果要从 A 导出,则可以使用:

If you want to derive it from A, you an use:

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

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

If you are able to use C++14 or a later version, you can simplify that to:

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

更多推荐

将const添加到引用

本文发布于:2023-11-05 21:34:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561916.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:const

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!