运行时返回参数包的成本效益方法

发布于 2025-01-30 11:40:23 字数 475 浏览 2 评论 0原文

这是一个我挠头的问题:我想返回variadic模板参数包的n个对象,而索引仅在运行时才知道。

我可以将每个参数放入元组中,然后访问元组,但是,Afaik带来了与参数列表的每个元素初始化元组的额外成本我真的不想付钱,因为它与我真正想做的事情不符。因此,我觉得必须有更好的方法。也许有一种方法可以在编译时间以某种方式进行预选?

我的代码意图:

#include <variant>
#include <iostream>


volatile int index = 2;

template <typename... Ts>
std::variant<Ts...> foo(Ts&&... args) {
    return { /* args[index] */ };
}

int main()
{
    foo(2, "hello", 3.4);
}

欢迎任何想法! :)

Here's a problem that I'm scratching my head over: I want to return the n-th object of a variadic template parameter pack whereas the index is known only at runtime.

I could just put every parameter in a tuple and then access the tuple, however, AFAIK this comes with the additional cost of initializing the tuple with every element of the argument list and even if its just moving the objects into the tuple that's still cost that I don't really feel like paying as it isn't aligned with what I actually want to do. So I feel there must be a better way. Maybe there's a way of preselecting the argument at compile time somehow?

My intention in code:

#include <variant>
#include <iostream>


volatile int index = 2;

template <typename... Ts>
std::variant<Ts...> foo(Ts&&... args) {
    return { /* args[index] */ };
}

int main()
{
    foo(2, "hello", 3.4);
}

Any ideas are welcome! :)

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文