我在这里看到了一些与
gcc bug有关的问题,它在lambda中捕获了可变参数.参见例如:
Does lambda capture support variadic template arguments或
Compiler bug, or non standard code? – Variadic template capture in lambda.我有以下设想的例子,我正在尝试做什么
#include <iostream>
#include <functional>
class TestVariadicLambda {
public:
template<typename... Args>
std::function<void()> getFunc(Args... args) {
return [=]{ printArgs(args...); };
}
template<typename T, typename... Args>
void printArgs(T value, Args... args) {
std::cout << value << ", ";
printArgs(args...);
}
void printArgs() {std::cout << "\n";}
};
在gcc 4.8.2中我收到以下错误:
../src/TestVariadicLambda.h: In lambda function:
../src/TestVariadicLambda.h:9:25: error: parameter packs not expanded with ‘...’:
return [=]{ printArgs(args...); };
^
../src/TestVariadicLambda.h:9:25: note: ‘args’
../src/TestVariadicLambda.h:9:29: error: expansion pattern ‘args’ contains no argument packs
return [=]{ printArgs(args...); };
^
我的问题是我如何解决这个问题,因为它不适用于gcc4.8
最佳答案 以下将有效.
#include <iostream>
#include <functional>
#include <vector>
std::string to_string(const char* s)
{
return s;
}
class Test
{
private:
void print() {}
public:
template<typename T, typename... Args>
void print(T value, Args... args)
{
std::cout << value << "\n";
print(args...);
}
template<typename... Args>
std::function<void()> getFunc(Args... args)
{
using namespace std;
std::vector<std::string> ArgumentList;
std::initializer_list<int> {(ArgumentList.push_back(to_string(args)), 0)...};
return [=] {for (const auto &t : ArgumentList){print(t);}};
}
};
int main()
{
Test().getFunc("Hey", 1, 2, 3.0f)();
}