首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态创建类型别名

动态创建类型别名
EN

Stack Overflow用户
提问于 2021-04-26 09:20:57
回答 1查看 31关注 0票数 0

具有类型别名

代码语言:javascript
复制
using MyVariantType = std::variant<int, double, std::string, bool>;

和别名模板,

代码语言:javascript
复制
template <typename T>
using MyFunctionType = std::function<bool(T)>

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

代码语言:javascript
复制
using MyFunctionVariantType = std::variant<MyFunctionType<int>, MyFunctionType<double>, MyFunctionType<std::string>, MyFunctionType<bool>>
EN

回答 1

Stack Overflow用户

发布于 2021-04-26 09:52:00

这段代码将从变体中获取每个类型,并将创建MyFunctionType的变体。它使用模板专门化来确定变体的类型:

代码语言:javascript
复制
#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>>>);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67259748

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档