首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从一组特征创建模板包

从一组特征创建模板包
EN

Stack Overflow用户
提问于 2020-10-24 02:11:38
回答 1查看 61关注 0票数 0

有没有可能(如果是的话,如何)从一组索引的类型特征中生成一个模板包,以便它们可以用来实例化一个变量或一个元组?

代码语言:javascript
复制
#include <variant>

template<int n>
struct IntToType;

template<>
struct IntToType<0>
{
    using type = int;
    static constexpr char const* name = "int";
//  Other compile-time metadata
};

template<>
struct IntToType<1>
{
    using type = double;
    static constexpr char const* name = "double";
//  Other compile-time metadata
};

using MyVariant = std::variant<IntToType<???>::type...>;  // something with make_integer_sequence and fold expression?

或者有必要使用变量作为输入:

代码语言:javascript
复制
#include <variant>

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

template<int n>
struct IntToTypeBase
{
    using type = std::variant_alternative_t<n, MyVariant>;
};

template<int >
struct IntToType;

template<>
struct IntToType<0>:IntToTypeBase<0>
{
    static constexpr char const* name = "int";
//  Other compile-time metadata
};

template<>
struct IntToType<1>:IntToTypeBase<1>
{
    static constexpr char const* name = "double";
//  Other compile-time metadata
};

或者甚至使用您自己的variant,它接受一组特征,而不是简单的类型列表:

代码语言:javascript
复制
template<class IntegerType, template<auto> class Traits, size_t LastIndex>
class Variant;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-24 02:24:32

你可以这样做:

代码语言:javascript
复制
#include <variant>

template<int n>
struct IntToType;

template<>
struct IntToType<0>
{
    using type = int;
    static constexpr char const* name = "int";
//  Other compile-time metadata
};

template<>
struct IntToType<1>
{
    using type = double;
    static constexpr char const* name = "double";
//  Other compile-time metadata
};

// replace NUMBER_OF_TYPES
template <typename T=std::make_index_sequence<NUMBER_OF_TYPES> >
struct make_my_variant;

template <size_t... indices>
struct make_my_variant<std::index_sequence<indices...> > {
    using type = std::variant<typename IntToType<indices>::type...>;
};

using MyVariant = typename std::make_my_variant<>::type;

注要查找字符串形式的typename,只需使用typeid(TYPE).name()即可。如果您愿意,您可能需要拆解这个名称;您可以使用编译器特定的拆解程序函数(我认为MSVC不会拆分类型名称,但在GCC系统中,您可以在<cxxabi.h>头中使用abi::__cxa_demangle )。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64505297

复制
相关文章

相似问题

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