My class has a member of a type optional<A>. I'm trying to implement function emplaceWhenReady which gets list of parameters to A's constructor, but the non-trivial part is that A can be only initialized after a certain event. When emplaceWhenReady is invoked before the event, I need to somehow capture the initialization values.
For single constructor parameter the code can be written as:
struct B {
bool _ready;
std::optional<A> _a;
std::function<void()> _fInit;
template<typename ARG>
void emplaceWhenReady1(ARG&& arg) {
if (_ready) {
_a.emplace(std::forward<ARG>(arg));
} else {
_fInit = [this, argCopy = std::forward<ARG>(arg)]() {
_a.emplace(std::move(argCopy));
};
}
};
and _fInit() can be now invoked when the class becomes _ready. But I fail to write similar code for multiple parameters:
// Fails to compile
template<typename... ARGS>
void emplaceWhenReady(ARGS&&... args) {
if (_ready) {
_a.emplace(std::forward<ARGS>(args)...);
} else {
_fInit = [this, argsCopy = std::forward<ARGS>(args)...]() {
_a.emplace(std::move(argsCopy)...);
};
}
}
Godbolt: https://godbolt.org/z/Fi3o1S
error: expected ',' or ']' in lambda capture list
_fInit = [this, argsCopy = std::forward<ARGS>(args)...]() {
^
Any help is appreciated!