具有独特类型的变体
Variant with unique types
本文关键字:类型 更新时间:2023-10-16
在编写 cpp 库时,我最终得出std::variant
s 应包含重复类型的可能性,例如,std::variant<int, double, int, std::string, int>
。它在某些情况下可能很有用,但在我的图书馆的情况下,我觉得这是不必要的。所以我想像这样过滤类型:
std::variant<int, double, int, std::string, int>
->std::variant<int, double, std::string>
std::variant<std::string, std::string, int>
->std::variant<std::string, int>
如何做到这一点?
#include <type_traits>
#include <variant>
template <typename T, typename... Ts>
struct filter_duplicates { using type = T; };
template <template <typename...> class C, typename... Ts, typename U, typename... Us>
struct filter_duplicates<C<Ts...>, U, Us...>
: std::conditional_t<(std::is_same_v<U, Ts> || ...)
, filter_duplicates<C<Ts...>, Us...>
, filter_duplicates<C<Ts..., U>, Us...>> {};
template <typename T>
struct unique_variant;
template <typename... Ts>
struct unique_variant<std::variant<Ts...>> : filter_duplicates<std::variant<>, Ts...> {};
template <typename T>
using unique_variant_t = typename unique_variant<T>::type;
演示
使用 Boost.Mp11,这是一个简短的单行代码(一如既往(:
using V1 = mp_unique<std::variant<int, double, int, std::string, int>>;
// V1 is std::variant<int, double, std::string>
using V2 = mp_unique<std::variant<std::string, std::string, int>>;
// V2 is std::variant<std::string, int>
我自己的版本使用 C++11(非提升(:
#include <type_traits>
template <typename T, typename... Args>
struct contains : std::integral_constant<bool, false> {};
template <typename T, typename T2, typename... Args>
struct contains<T, T2, Args...> : contains<T, Args...> {};
template <typename T, typename... Args>
struct contains<T, T, Args...> : std::integral_constant<bool, true> {};
template <typename W, typename... Ts>
struct __make_unique_impl {
using type = W;
};
template <template <typename...> class W, typename... Current, typename T,
typename... Ts>
struct __make_unique_impl<W<Current...>, T, Ts...>
: std::conditional<
contains<T, Ts...>::value,
typename __make_unique_impl<W<Current...>, Ts...>::type,
typename __make_unique_impl<W<Current..., T>, Ts...>::type> {};
template <typename W>
struct make_unique;
template <template <typename...> class W, typename... T>
struct make_unique<W<T...>> : __make_unique_impl<W<>, T...> {};
如何使用:
#include <variant>
using test_t = typename make_unique<std::variant<int, std::string, std::string, int>>::type; // std::variant<int, std::string>
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 类中的字符串不命名类型