从一组特征创建模板包 [英] Create template pack from set of traits
问题描述
是否可以(如果可以,如何)从一组索引的类型特征生成模板包,以便它们可以用于实例化变体或元组?
Is it possible (and if so, how) to generate a template pack from a indexed set of type traits so they can be used to instantiate a variant or a tuple?
#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?
或者是否有必要使用变体作为输入:
Or is it necessary to use the variant as input instead:
#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
,它接受一组特征而不是一个简单的类型列表:
or even roll your own variant
, which accepts a set of traits instead of a plain list of type:
template<class IntegerType, template<auto> class Traits, size_t LastIndex>
class Variant;
推荐答案
您可以:
#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;
注意要以字符串文字形式查找类型名称,您可以使用 typeid(TYPE).name()
.如果您愿意,您可能需要修改此名称;您可以使用特定于编译器的 demangler 函数(我认为 MSVC 不会修改类型名称,但是在 GCC 上,您可以在 <cxxabi.h>
中使用 abi::__cxa_demangle
> 标题.)
Note to find the typename as a string literal, you could just use typeid(TYPE).name()
. You may need to demangle this name, if you wish; you can use your compiler-specific demangler function (I think MSVC doesn't mangle type names, but on GCC you would use abi::__cxa_demangle
in <cxxabi.h>
header.)
这篇关于从一组特征创建模板包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!