0%

C++ 不定参数到 lambda 的传递

使用 不定参数列表传递到 lambda 中总是报错,这里记录一下正确用法

1
2
3
4
5
6
7
8
9
template<class T, class... Args>
void ObjectPool::SetType(std::string type, Args&&... args)
{
m_mapAlloc[type].m_construct = [& args...](IRecyclable* p) {
std::allocator<T> alloc;
std::allocator_traits<std::allocator<T>> traits;
traits.construct(alloc, static_cast<T*>(p), args...);
};
}

以上代码是正确的使用方法,对于不定参数 Args&&... args 在函数中使用时一定都是带上 ... 使用的

刚开始报错就是我在 lambda 捕获列表中一直写的是 [&args], 而且后面传入 construct 函数时也需要使用 args... 或者使用 std::move(args)...

关于 lambda 捕获,可以参考 Lambda 表达式 (C++11 起) - cppreference.com

关于 不定参数,可以参考 [形参包 - cppreference.com]

包展开:

1
2
3
4
5
6
7
f(&args...); // 展开成 f(&E1, &E2, &E3)
f(n, ++args...); // 展开成 f(n, ++E1, ++E2, ++E3);
f(++args..., n); // 展开成 f(++E1, ++E2, ++E3, n);
f(const_cast<const Args*>(&args)...);
// f(const_cast<const E1*>(&X1), const_cast<const E2*>(&X2), const_cast<const E3*>(&X3))
f(h(args...) + args...); // 展开成
// f(h(E1,E2,E3) + E1, h(E1,E2,E3) + E2, h(E1,E2,E3) + E3)