微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

动态创建类型别名

如何解决动态创建类型别名

一个类型别名

using MyVariantType = std::variant<int,double,std::string,bool>;

和别名模板,

template <typename T>
using MyFunctionType = std::function<bool(T)>

如何从 MyVariantTypeMyFunctionType 动态创建以下类型别名?

using MyFunctionVariantType = std::variant<MyFunctionType<int>,MyFunctionType<double>,MyFunctionType<std::string>,MyFunctionType<bool>>

解决方法

此代码段将从变体中获取每种类型,并将创建 MyFunctionType 的变体。它与模板特化一起工作以找出变体的类型:

#include <variant>
#include <functional>

using MyVariantType = std::variant<int,double>;

template <typename T>
using MyFunctionType = std::function<bool(T)>;

/// Helper struct to create the FunctionType from the Varaint Type
template <typename T>
struct CreateFunctionVariant;
template <typename... Ts>
struct CreateFunctionVariant<std::variant<Ts...>>
{
    using Type = std::variant<MyFunctionType<Ts>...>;
};
using MyFunctionVariantType = CreateFunctionVariant<MyVariantType>::Type;

/// Make sure it actually produces the right type
static_assert(std::is_same_v<MyFunctionVariantType,std::variant<MyFunctionType<int>,MyFunctionType<double>>>);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。