使用可变参数模板建立索引
假设我有一个正在展开的参数包,例如
template<typename... P> void f(P...&& args) {
some_other_func(std::forward<P>(args)...);
}
现在假设我还有这些对象需要执行的其他一些次要功能。
template<typename T> T&& some_func(T&& ref) {
// replace with actual logic
return std::forward<T>(ref);
}
我通常会替换为
template<typename... P> void f(P...&& args) {
some_other_func(some_func(args)...);
}
但是,如果 some_func
需要有关参数的更多信息而不仅仅是其类型,例如它在参数包中的数字位置,我该怎么办?这样我就可以将其扩展到
some_other_func(some_func(arg1), some_func(arg2));
而不是扩展到?
some_other_func(some_func(arg1, 1), some_func(arg2, 2));
例如,
Let's say that I have a parameter pack I'm unrolling, e.g.
template<typename... P> void f(P...&& args) {
some_other_func(std::forward<P>(args)...);
}
Now let's say that I have some other minor function that these objects need to go through.
template<typename T> T&& some_func(T&& ref) {
// replace with actual logic
return std::forward<T>(ref);
}
I would normally just replace with
template<typename... P> void f(P...&& args) {
some_other_func(some_func(args)...);
}
But what do I do if some_func
requires more information about the parameter than just it's type, like for example, it's position numerically in the parameter pack? So that instead of expanding to
some_other_func(some_func(arg1), some_func(arg2));
I could mke it expand to
some_other_func(some_func(arg1, 1), some_func(arg2, 2));
for example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道我以前解决过这个问题,但不记得是怎么解决的。哦,好吧,这是一个新鲜的外观。
数字序列可以使用 std::get 转换为参数序列,因此更为基础。因此,假设我需要实现某种自定义工具,数字包生成器似乎是一个不错的选择。
(啊,这太乏味了。我确实看了 Howard 的答案并了解了
forward_as_tuple
,但该函数在我的编译器或 ideone.com 上还不存在,所以废话。有很多我仍然需要弄清楚一些事情,这无疑是有史以来最糟糕的函数式语言之一。)http://ideone.com/u5noV
I know I've solved this before but can't recall how. Oh well, here's a fresh look.
The sequence of numbers can be translated into the argument sequence using
std::get
, so it is more fundamental. So, assuming that I need to implement some kind of custom tool, a number pack generator seems like a good choice.(Gah, this was incredibly tedious. I did peek at Howard's answer and learned about
forward_as_tuple
, but that function doesn't even exist yet on my compiler or ideone.com, so blah. There are a lot of things I still need to get straight, and this is certainly one of the worst functional languages ever invented.)http://ideone.com/u5noV
这有点复杂。但这里是使用 libc++ 的几个私有实用程序的代码的工作原型,可以在 。
<__tuple> 和
It is a little convoluted. But here is a working prototype of your code using several private utilities of libc++, found in
<__tuple>, and <tuple>.