可变参数模板根据未知数量的参数返回 N 元组

发布于 2025-01-18 06:31:23 字数 682 浏览 1 评论 0原文

我想要一个可变参数函数模板,它接受某种类型 T 的指针,填充这些指针,并为每个指针生成一个对象作为结果,最终结果是所有这些生成的对象的元组。

给定一个库中的函数(使用 C api):

struct opaque {};

bool fill_pointer(opaque **);

并且:

struct MyType {};

MyType gen_object(opaque *);

我想要一个可变参数模板函数,看起来像这样(有点):(

std::tuple<bool, MyType...> fill_and_gen_objects(opaque **...);

其中 bool 结果是 false 当且仅当 fill_pointer 返回值之一为 false 时)。

这就是我想要实现的目标:

opaque *oa, *ob, *oc;
auto [failed, ta, tb, tc] = fill_and_gen_objects(oa, ob, oc);

谢谢

I would like to have a variadic function template that takes pointers of a certain type T, fills those pointers, and for each of them generate an object as a result, the final result being a tuple of all these generated objects.

Given a function from a library (that uses a C api):

struct opaque {};

bool fill_pointer(opaque **);

And:

struct MyType {};

MyType gen_object(opaque *);

I would like to have a variadic template function that would look like this (sort of):

std::tuple<bool, MyType...> fill_and_gen_objects(opaque **...);

(where the bool result is false if and only one of fill_pointer return value is false).

This is what I would like to achieve:

opaque *oa, *ob, *oc;
auto [failed, ta, tb, tc] = fill_and_gen_objects(oa, ob, oc);

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

山色无中 2025-01-25 06:31:23

continue

That's heavy pseudocode, I'll answer with heavy pseudocode:

template<typename ... Ts>
constexpr auto fill_and_gen_objects(Ts* ... os)
{ 
    bool some_status = true; //whatever
    return std::make_tuple(some_status, gen_object(os) ...);
}

Ok, actually it even compiles, see here

EDIT: downgraded to C++14 ... that's what you've tagged.


Same for C++17 using CTAD

template<typename ... Ts>
constexpr auto fill_and_gen_objects(Ts* ... os)
{ 
    bool some_status = true; //whatever
    return std::tuple{some_status, gen_object(os) ...};
}

Same for C++20 using abbreviated function template syntax

constexpr auto fill_and_gen_objects(auto* ... os)
{ 
    bool some_status = true; //whatever
    return std::tuple{some_status, gen_object(os) ...};
}

C++20 with indices by using integer sequence (untested):

constexpr auto fill_and_gen_objects(auto* ... os)
{ 
    bool some_status = true; //whatever
    return []<int ... I>(std::index_sequence<I...>, auto tup){ return std::tuple{some_status, gen_object(std::get<I>(tup)) ...};}
    (std::make_index_sequence<sizeof...(os)>{}, std::tuple{os...})
}

Furthermore, here is the C++27 solution:

void do_my_fckng_work() { bool asap = true; }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文