环境:vs2013 rc5 / vs2017;<br>项目:win32控制台应用;</p>
表示:编译运行一会儿,然后中断观察变量“task_”;
如果 func main 中的“add_task(&Test::print, &t, str, 10)”,则“task_”是正确的值;
但是如果 func mytest 中的“add_task(&Test::print, &t, str, 10)”,则“task_”的值是错误的;如果将 std::cin.get() 替换为 while(1){},则右转;
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include <functional>
using task_t = std::function<void()>;
class Test
{
public:
void print(const std::string& str, int i)
{
std::cout << "Test: " << str << ", i: " << i << std::endl;
}
};
template<typename Function, typename Self, typename... Args>
void add_task(const Function& func, Self* self, Args... args)
{
task_t task = [&func, &self, args...]{ return (*self.*func)(args...); };
task_ = task;
}
Test t;
std::string str = "Hello world";
task_t task_ = nullptr;
void mytest()
{
add_task(&Test::print, &t, str, 10);
}
int main()
{
mytest();
std::cin.get();
return 0;
}