gpt4 book ai didi

c++ - 提升多种可能性的变体

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:51:42 24 4
gpt4 key购买 nike

假设我有一个模板类,大小超过一种类型:

template<size_t N, typename T>
class C
{};

我想生成一个 boost::variant,它能够将此类保存在多种大小和类型上,例如对于大小 12 以及类型 intunsigned int 它将是

typedef boost::variant<
C<1, int>,
C<1, unsigned int>,
C<2, int>,
C<2, unsigned int>
> my_variant;

问题是我在几个地方需要这个设置,每次都需要不同的大小和类型。是否有一些模板元编程魔法可以从可能值列表中生成这些变体,类似于

typedef generate_variant<C, 1, 2, int, unsigned int>::type my_variant;

最佳答案

好的,我做到了。方法如下:

#include <boost/variant.hpp>
#include <tuple>
#include <iostream>
#include <typeinfo>

template<size_t N, typename T>
class C
{};

template<template <size_t, class> class T>
struct combine
{
template<size_t... Ns> struct sizes;

template<size_t N>
struct sizes<N>
{
template<typename... Types>
struct types
{
typedef std::tuple<T<N, Types>...> type;
};
};

template<size_t N, size_t... Ns>
struct sizes<N, Ns...>
{
template<typename... Types>
struct types
{
typedef typename sizes<N>::template types<Types...>::type head;
typedef typename sizes<Ns...>::template types<Types...>::type tail;
typedef decltype(std::tuple_cat<head, tail>(std::declval<head>(), std::declval<tail>())) type;
};
};
};

template<typename... Types>
auto to_variant(const std::tuple<Types...>&)
{
return boost::variant<Types...>();
}

struct typename_visitor : public boost::static_visitor<>
{
template<size_t N, typename T>
void operator()(const C<N, T>& c)
{
std::cout << "C<" << N << ", " << typeid(T).name() << ">\n";
}
};

int main()
{
combine<C>::sizes<1, 2>::types<int, unsigned int>::type v;
auto var = to_variant(v);
var = C<1, int>();
// var = C<3, int>(); // doesn't compile
// var = C<1, short>(); // doesn't compile
var.apply_visitor(typename_visitor()); // prints C<1, int>
}

关于c++ - 提升多种可能性的变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35920060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com