void func(const std::string& args)
{
// Statically initialize a vector of lambdas (only one here for now)
// The lambdas capture by reference with[&], but since the
// initializer list is static (and thus initialized only once), how
// will the lambda be able to access args with each successive call to func()?
// Won't there be undefined behavior with this?
static std::vector<std::function<void()>> FuncMap =
{
// args (and everything else in scope) will be captured by reference
{ [&]() { for(const auto& s: args) std::cout << s << std::endl; }}
};
auto f = FuncMap[0];
f();
}
答案 0 :(得分:1)
我不知道你是出于好奇而问这个问题,还是你真的想要做这样的事情。如果是后者,这是一个可能的解决方案:
void func(const std::string& args)
{
static std::string const * pargs;
static std::vector<std::function<void()>> FuncMap =
{
{ [&]() { for(const auto& s: *pargs) std::cout << s << std::endl; }}
};
pargs = &args;
auto f = FuncMap[0];
f();
}