将常量添加到引用
Add const to reference
我想通过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
,而不是A
的int
部分。由于引用在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>()));
相关文章:
- CMake VS_PACKAGE_REFERENCES不添加对 VS2017 项目的引用
- 将新元素添加到列表中,并返回对该元素的引用?
- 本机 Nuget 包安装在 VS 中,但没有为C++(本机)项目添加引用
- 将常量添加到引用
- 为什么在此 CRTP 基函数调用中添加引用会消除错误?
- 在 ONE 设置中添加附加包含目录并引用 => 指向静态库
- 在C++中向地图添加对对象的引用
- 对成员变量的引用在向同一向量中添加另一个实例后断开
- 是否有一种方法可以将C 类成员引用到向量而不明确添加它们
- 处理受向 std::vector 添加元素影响的引用
- 如何将非托管库引用添加到 NUnit 测试
- 为什么添加对右值引用的引用不是错误
- 当通过引用传递时,通过传递链表在第n个位置添加元素不起作用
- 在 CMake CMakeLists.txt 中添加对 NewT 的库引用
- 添加到字符串数组和引用
- 添加了对 .lib 项目的引用 - 项目不使用.cpp文件
- 为什么Qt会向相对不被引用的库添加'PWD'?
- 添加控制器引用/指向c++单例类的指针
- 将函数引用添加到列表中
- Visual C# - 引用 > 添加引用... > COM:该列表是如何填充的?