【发布时间】:2018-10-28 16:08:43
【问题描述】:
我的班级有一个optional<A> 类型的成员。我正在尝试实现函数emplaceWhenReady,它获取A的构造函数的参数列表,但重要的部分是A只能在某个事件之后初始化。在事件之前调用emplaceWhenReady 时,我需要以某种方式捕获初始化值。
对于单个构造函数参数,代码可以写成:
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));
};
}
};
现在可以在类变为_ready 时调用_fInit()。但是我没有为多个参数编写类似的代码:
// 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)...);
};
}
}
天箭:https://godbolt.org/z/Fi3o1S
error: expected ',' or ']' in lambda capture list
_fInit = [this, argsCopy = std::forward<ARGS>(args)...]() {
^
感谢任何帮助!
【问题讨论】:
-
我不太明白如何测试,你想在 optional 中放置一个可变参数列表?
-
你知道
std::function强加了可复制性要求吗?不管怎样,看看<tuple>,特别是std::apply()。 -
@ShafikYaghmour 谢谢,但从我看来,这个问题的问题是不同的,因为他们只需要将参数转发到 lambda 中,而不需要捕获参数的副本
-
:-( 这就是我得到的速度评论
-
@Deduplicator 我创建了一个使用
make_tuple存储参数副本的版本,它使用std::apply,正如您所建议的:godbolt.org/z/qC7I8L 对我来说似乎是一个可行的解决方案,谢谢!跨度>