添加const到引用

R z*_* zu 6 c++ templates const

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

不知怎的,它不起作用.这在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;
}
Run Code Online (Sandbox Code Playgroud)

编译错误:

add2.cpp:5:1: error: static assertion failed: is const
 static_assert(std::is_const<typename std::remove_reference<
 ^~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 13

不知怎的,它不起作用.这在c ++中是不可能的吗?

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

typedef int& A;
typedef const A B;
Run Code Online (Sandbox Code Playgroud)

不翻译成

typedef int& A;
typedef const int& B;
Run Code Online (Sandbox Code Playgroud)

const

typedef const A B;
Run Code Online (Sandbox Code Playgroud)

适用于A,不是int的一部分A.由于引用在C++中是不可变的,const A因此与A类型点视图相同.


您可以使用:

typedef int const& B;
Run Code Online (Sandbox Code Playgroud)

如果你想从中派生出来A,你可以使用:

using B = typename std::remove_reference<A>::type const&;
Run Code Online (Sandbox Code Playgroud)

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

using B = std::remove_reference_t<A> const&;
Run Code Online (Sandbox Code Playgroud)

  • West const再次失败. (3认同)