将const添加到引用 [英] Add const to reference
本文介绍了将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添加到引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文