c++ - 结构数据成员的decltype,使用结构化绑定
问题描述
我有一个模板采用在结构上可绑定到两个别名的类型(可以是元组,也可以是结构)。我需要别名指向的这两个变量的类型。
template <typename T>
T obj;
// type of a/b in auto&& [a, b] = obj ?
在实际使用结构化绑定之前,我需要知道类型:
template <typename S>
void fn(ranges::any_view<S> range_of_tuple_or_struct_or_pair) {
last_from = std::numeric_limits<?????>::max();
// ????? should be the type of from (or to, they should be the same types) of:
// auto&& [from, to] = <range element>
for (auto&& [from, to] : range_of_tuple_or_struct_or_pair) {
if (from != last_from) {
...;
last_from = from;
}
}
}
解决方案
我认为你可以这样做:
#include <type_traits>
template <typename T, typename U>
struct Identity {
using type_first = T;
using type_second = U;
};
template <typename T>
constexpr auto GetTypes(const T& obj) noexcept {
const auto& [x, y] = obj;
return Identity<std::remove_cv_t<decltype(x)>,
std::remove_cv_t<decltype(y)>>{};
}
template <typename T>
void foo(T obj) {
// T is structurally-bindable with two fields
constexpr auto Types = GetTypes(obj);
using t1 = typename decltype(Types)::type_first;
using t2 = typename decltype(Types)::type_second;
// t1 is the first type
// t2 is the second type
}
请注意constexpr
,即使没有启用优化,也没有开销。
推荐阅读
- maven - 如何在 Maven 属性中转义特殊字符
- regex - 正则表达式 - tagmanager - 过滤子目录的最佳方法
- firebase - 在同一应用程序中将 google 数据存储更改为 Firestore
- regex - 在 Hive 中使用正则表达式获取匹配数?
- excel - 粘贴范围返回变量范围的语法错误
- java - 合并排序和数组
- macos - Mac OS X 10.6 Swift 4.2 Xcode 10.0:此类与键的键值编码不兼容
- javascript - WKWebview evaluateJavaScript in swift 仅适用于某些网站
- android - 在 Android 的另一个程序中访问选定的文本
- c# - 带有图形的自动滚动面板