具有类型别名
using MyVariantType = std::variant<int, double, std::string, bool>;和别名模板,
template <typename T>
using MyFunctionType = std::function<bool(T)>如何从MyVariantType和MyFunctionType动态创建以下类型别名
using MyFunctionVariantType = std::variant<MyFunctionType<int>, MyFunctionType<double>, MyFunctionType<std::string>, MyFunctionType<bool>>发布于 2021-04-26 09:52:00
这段代码将从变体中获取每个类型,并将创建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>>>);https://stackoverflow.com/questions/67259748
复制相似问题