我有包装任意lambda并返回lambda结果的C++代码。
template <typename F>
auto wrapAndRun(F fn) -> decltype(F()) {
// foo();
auto result = fn();
// bar();
return result;
}除非F返回void (error: variable has incomplete type 'void'),否则这会起作用。我想过使用ScopeGuard来运行bar,但我不希望bar在fn抛出异常时运行。有什么想法吗?
另外,我后来发现有个叫a proposal to fix this inconsistency的人。
发布于 2017-12-28 02:04:48
这是一个非常笨拙且不可扩展的解决方案,但它非常简短,而且它支持RVO,这对于一些返回类型可能很重要:
template <typename F>
auto wrapAndRun(F fn) -> decltype(F()) {
// foo();
char c;
auto runner = std::unique_ptr<char, decltype(bar)>( &c, bar );
try {
return fn();
}
catch( ... ) {
runner.release();
throw;
}
}https://stackoverflow.com/questions/47996550
复制相似问题