gpt4 book ai didi

c++ - 从类型列表到参数包

转载 作者:行者123 更新时间:2023-11-30 04:02:42 25 4
gpt4 key购买 nike

我有一个此处描述的形式的类型列表:

http://www.drdobbs.com/generic-programmingtypelists-and-applica/184403813

每个类型都有一个名为 get() 的鸭子类型函数(模板/编译时虚拟),它返回一个简单类型,如下所示:

struct Float {
float get() { return 7.0; }
};
struct Int {
int get() { return 7; }
};
typedef typelist<Float, typelist<Int, null_typelist>> types;

我还有一个函数,它接受可变数量的简单类型参数,如下所示:

template<typename... Args>
foo(Args... args)
{
}

现在我需要一种方法来调用给定 typesfoo。我认为通过元组可以解决这个问题,但我离有效的解决方案还很远......我希望你能在这里帮助我!

最佳答案

此代码将 typelist 转换为 tuple 并使用简单类型调用 foo

#include <tuple>
#include <iostream>

template<typename H, typename T>
struct typelist
{
typedef H Head;
typedef T Tail;
};

struct null_typelist {};


template<int... Indices>
struct indices {
using next = indices<Indices..., sizeof...(Indices)>;
};

template<int Size>
struct build_indices {
using type = typename build_indices<Size - 1>::type::next;
};

template<>
struct build_indices<0> {
using type = indices<>;
};

template<typename T>
using Bare = typename std::remove_cv<typename std::remove_reference<T>::type>::type;

template<typename Tuple>
constexpr
typename build_indices<std::tuple_size<Bare<Tuple>>::value>::type
make_indices()
{ return {}; }

template<typename T, typename... Args>
struct tuple_push;

template<typename T, typename... Args>
struct tuple_push<T, std::tuple<Args...>>
{
typedef std::tuple<Args..., T> type;
};

template<typename TL>
struct typelist_to_tuple;

template<typename H, typename T>
struct typelist_to_tuple<typelist<H, T>>
{
typedef typename tuple_push<H, typename typelist_to_tuple<T>::type>::type type;
};

template<typename H>
struct typelist_to_tuple<typelist<H, null_typelist>>
{
typedef std::tuple<H> type;
};

struct Float {
float get() const { return 7.5; }
};
struct Int {
int get() const { return 7; }
};

template<typename... Args>
void foo(const Args&... args)
{
}

template<typename T, typename... Args>
void foo(const T& current, const Args&... args)
{
std::cout << current << std::endl;
foo(args...);
}

template<typename Tuple, int... Indices>
void apply(const Tuple& tuple, indices<Indices...>)
{
foo(std::get<Indices>(tuple).get()...);
}

template<typename Tuple>
void apply(const Tuple& tuple)
{
apply(tuple, make_indices<Tuple>());
}

int main()
{
typedef typelist<Int, typelist<Float, typelist<Int, null_typelist>>> list;
typedef typelist_to_tuple<list>::type tuple;
tuple t = std::make_tuple(Int(), Float(), Int());
apply(t);
}

live example

关于c++ - 从类型列表到参数包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24931087/

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