通用参考捕获 [英] Capture by universal reference

查看:46
本文介绍了通用参考捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当将推导类型作为r值引用传递时,我将获得通用引用功能,并且可以像这样归档完美的转发:

When passing a deduced type as r-value reference I get universal reference functionality and can archieve perfect forwarding like this:

template <typename T>
void func(T&& t) {
    other_func(std::forward<T>(t));
}

...由于T的导出方式和标准的参考折叠规则.

...due to the way T is derived and the standard's reference collapse rules.

现在考虑other_func接受一个函数对象

Now consider other_func takes a function object

template <typename T>
void func(T&& t) {
    other_func([](int v) { return t + v; }); // I chose addition for example purposes
}

现在显然由于未被捕获,因此无法编译.我的问题是:我该如何捕获它,以便捕获的值将等于推论得出的T值?

Now obviously this won't compile due to t not being captured. My question is: How do I capture it so the captured value will be whatever T is deduced to?

使用新的通用lambda捕获有可能吗?如果...怎么办?

Is this possible using the new generic lambda captures? And if... how?

[t = std::forward<T>(t)] ? 

我仍然还不太了解新的捕获初始化程序的机制...

I still don't really get the mechanics of the new capture initializers...

推荐答案

您可以在C ++ 11中通过通用引用捕获",因为模板参数 T 的类型可用于lambda函数( Coliru上隐藏的实时代码示例):

You can "capture by universal reference" in C++11, since the type of the template parameter T is available to the lambda function (hideous live code example at Coliru):

template <typename T>
void func(T&& t) {
  other_func([&t](int v) {
    return std::forward<T>(t) + v;
  });
}

这篇关于通用参考捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆