Seb*_*n.M 3 c++ lambda variadic-templates
所以我有一个可变参数模板类,它有一个方法,用于在lambda中捕获模板的参数.后来叫lambda.问题是,无论是在包的前面还是后面,它都会失去价值.
这是一个简化的例子:
#include <iostream>
#include <functional>
void doPrint() {}
template <typename Arg, typename... Args>
void doPrint(Arg arg, Args... args) {
std::cout << arg << std::endl;
doPrint(std::forward<Args>(args)...);
}
template <typename... Args>
void print(Args... args) {
doPrint(std::forward<Args>(args)...);
}
class IntWrapper {
public:
IntWrapper(int val) : val(val) {}
int val;
};
std::ostream& operator<<(std::ostream& out, const IntWrapper& value) {
out << value.val;
return out;
}
template <typename... Args>
class TestClass {
public:
void createWrapper(Args... args) {
wrapper = [&]() -> void {
print(std::forward<Args>(args)...);
};
}
std::function<void()> wrapper;
};
int main(int argc, char *argv[])
{
std::string string = "abc";
std::cout << "Test 1:" << std::endl;
TestClass<int, const IntWrapper&, int> test1;
test1.createWrapper(1, IntWrapper(2), 3);
test1.wrapper();
std::cout << std::endl << "Test 2:" << std::endl;
TestClass<int, const IntWrapper&> test2;
test2.createWrapper(1, IntWrapper(2));
test2.wrapper();
std::cout << std::endl << "Test 3:" << std::endl;
TestClass<const IntWrapper&, int> test3;
test3.createWrapper(IntWrapper(1), 2);
test3.wrapper();
std::cout << std::endl << "Test 4:" << std::endl;
TestClass<const IntWrapper&, int, const IntWrapper&> test4;
test4.createWrapper(IntWrapper(1), 2, IntWrapper(3));
test4.wrapper();
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出:
Test 1:
1
2
3
Test 2:
32764
2
Test 3:
1
32764
Test 4:
1
0
3
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,包装的int总是保持它们的值,但是int有时却没有.我知道如果我通过副本捕获并且不使用向前它是有效的,但我不能在我的实际用例中这样做.
那么,为什么这不起作用?有没有办法解决它?
编辑:好吧,好吧,显然我让变量超出示例中的范围是愚蠢的.它适用于局部变量.但是,问题仍然出现在我的用例中,其中变量不在范围之外.我会尝试将问题转移到我的示例中,然后再试一次.
所以发生的事情是你的引用在你使用它们之前超出了范围.
test1.createWrapper(1, IntWrapper(2), 3);
Run Code Online (Sandbox Code Playgroud)
到达时,您传递的所有变量都超出了范围
test1.wrapper();
Run Code Online (Sandbox Code Playgroud)
如果你把它们存储在本地然后调用,就像
int x = 1, z = 3;
IntWrapper y(2);
test1.createWrapper(x, y, z);
test1.wrapper();
它应该工作.对于您的实际代码,您需要确保从调用createWrapper到调用包装器时值仍然有效,或者您需要在createWrapper中按值捕获.
编辑:
我错过了这个:
TestClass<int, const IntWrapper&, int> test1;
Run Code Online (Sandbox Code Playgroud)
对于test1,你没有转发传入的int(在上面的例子中是x和z)你转发了x和z的副本,因为那些int是按值传递的.如果你改为
TestClass<int&, const IntWrapper&, int&> test1;
Run Code Online (Sandbox Code Playgroud)
那我觉得它会奏效.