有没有可能(如果是的话,如何)从一组索引的类型特征中生成一个模板包,以便它们可以用来实例化一个变量或一个元组?
#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?或者有必要使用变量作为输入:
#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,它接受一组特征,而不是简单的类型列表:
template<class IntegerType, template<auto> class Traits, size_t LastIndex>
class Variant;发布于 2020-10-24 02:24:32
你可以这样做:
#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 )。
https://stackoverflow.com/questions/64505297
复制相似问题