c++ - 如何编写将一种类型的指针/引用/限定符复制到另一种类型的元函数?
问题描述
我是 C++ 和模板的新手,想编写一个元函数,将一种类型的指针/引用/限定符复制到另一种类型(C++17/20)。
例如,some_func<const A*, A, B>
生成const B*
,some_func<A*&&, A, B>
生成B*&&
。some_fun
无论*/&/const
提供多少都应该是有效的。
解决方案
您可以使用模板部分专业化来做到这一点。
template <typename X, typename Y>
struct some_func {
using type = Y;
};
template <typename X, typename Y>
struct some_func<const X*, Y> {
using type = const Y*;
};
template <typename X, typename Y>
struct some_func<X*&&, Y> {
using type = Y*&&;
};
// ...
template <typename X, typename Y>
using some_func_t = some_func<X, Y>::type;
static_assert(std::is_same_v<some_func_t<const int *, float>, const float*>);
static_assert(std::is_same_v<some_func_t<int*&&, float>, float*&&>);
推荐阅读
- typescript - 如何使用该 xpath 对元素设置操作?
- laravel - Laravel 5.8 请求数据为空
- android - GridView 没有全屏显示
- angular - Mat-Button routerLinkActive 替代方案?
- command-line - 意外标记“(”附近的语法错误,带有 gdbserver 的引用参数
- react-native - React native error "unsupported BodyInit type" 为什么会出现以及如何解决?
- arrays - ClickHouse 数组 - 在数组中找到最长的重复数字链
- ios - IOS 目标 C 选择器使用了错误的范围
- node.js - 无法访问全局安装的节点模块
- .net - ASP.NET Core 2.2 升级到 Core 3.0 后,我的 OnModelCreating 方法出现错误