gpt4 book ai didi

c++ - 使结构表现得像 std::tuple

转载 作者:行者123 更新时间:2023-11-27 23:48:29 26 4
gpt4 key购买 nike

我写了一些管理元组列表的通用代码。现在我想使用该代码,但我想使用简单的结构而不是 std::tuple,这样我就可以使用名称而不是索引来访问变量。有没有一种简单的方法可以使这些结构的行为类似于 std::tuple,以便我可以将它与我的通用代码一起使用?

struct foo {
int x;
float y;

// some code to enable tuple like behavior (e.g. std::get, std::tuple_size)
};

我已经尝试添加一个 as_tuple 成员函数,它使用 std::tie 返回所有成员。这可行,但需要在我需要元组行为的所有地方调用此成员函数。

最佳答案

手动方式:

struct foo {
int x;
float y;
};


namespace std
{

template <>
class tuple_element<0, foo> {
using type = int;
};

template <>
class tuple_element<1, foo> {
using type = float;
};

template <std::size_t I>
tuple_element_t<I, foo>& get(foo&);

template <>
tuple_element_t<0, foo>& get(foo& f) { return f.x;}

template <>
tuple_element_t<1, foo>& get(foo& f) { return f.y; }

template <std::size_t I>
tuple_element_t<I, foo> get(const foo&);

template <>
tuple_element_t<0, foo> get(const foo& f) { return f.x;}

template <>
tuple_element_t<1, foo> get(const foo& f) { return f.y; }
}

另一种方法是编写函数as_tuple:

template <typename ... Ts>
std::tuple<Ts...>& as_tuple(std::tuple<Ts...>& tuple) { return tuple; }

std::tuple<int&, float&> as_tuple(foo& f) { return std::tie(f.x, f.y); }

并在使用类元组之前包装您的电话。

关于c++ - 使结构表现得像 std::tuple,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48623432/

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