有时我需要一个无效的虚拟上下文管理器.然后,它可以用作更有用但可选的上下文管理器的替身.例如:
ctx_mgr = <meaningfulContextManager> if <condition> else <nullContextManager>
with ctx_mgr:
...
Run Code Online (Sandbox Code Playgroud)
如何定义这样一个简单的空上下文管理器?Python库是否提供现成的?
我们希望将上下文与as子句一起使用的情况如何?
with ctx_mgr as resource:
<operations on resource>
Run Code Online (Sandbox Code Playgroud) 正如事实证明,condition_variable::wait_for的确可以称为condition_variable::wait_for_or_possibly_indefinitely_longer_than,因为它需要之前确实超时并返回到重新获取锁.
请参阅此程序以进行演示.
有没有办法表达,"看,我真的只有两秒钟.如果myPredicate()当时仍然是假的和/或锁仍然锁定,我不在乎,只是随身携带,并给我一个方法来检测那."
就像是:
bool myPredicate();
auto sec = std::chrono::seconds(1);
bool pred;
std::condition_variable::cv_status timedOut;
std::tie( pred, timedOut ) =
cv.really_wait_for_no_longer_than( lck, 2*sec, myPredicate );
if( lck.owns_lock() ) {
// Can use mutexed resource.
// ...
lck.unlock();
} else {
// Cannot use mutexed resource. Deal with it.
};
Run Code Online (Sandbox Code Playgroud) 我认为这个问题有点被误解了.
回归const价值并不是可以被视为毫无意义的东西.正如Adam Burry在评论中指出的那样,Scott Meyers在更有效的C++(第6项)中推荐它,我将添加Herb Sutter的Exceptional C++(第20项,类机械,其相应的GotW 可在线获得).
这样做的理由是你希望编译器能够捕获像(a+b)=c(oops,意思==)或误导性语句这样的错别字a++++,这两种语句都被标记为开箱即用的原始类型int.因此,对于喜欢的东西operator+和operator++(int),返回const值有一定道理.
另一方面,正如已经指出的那样,返回a会const阻止C++ 11的移动语义,因为它们需要非const右值引用.
所以我的问题是,我们真的不能吃蛋糕吗?(我找不到办法.)
在 Python 中,按照惯例,下划线 ( _) 通常用于丢弃解包元组的一部分,如下所示
>>> tup = (1,2,3)
>>> meaningfulVariableName,_,_ = tup
>>> meaningfulVariableName
1
Run Code Online (Sandbox Code Playgroud)
我正在尝试对 lambda 的元组参数执行相同的操作。只能用 2 元组来完成这似乎不公平......
>>> map(lambda (meaningfulVariableName,_): meaningfulVariableName*2, [(1,10), (2,20), (3,30)]) # This is fine
[2, 4, 6]
>>> map(lambda (meaningfulVariableName,_,_): meaningfulVariableName*2, [(1,10,100), (2,20,200), (3,30,300)]) # But I need this!
SyntaxError: duplicate argument '_' in function definition (<pyshell#24>, line 1)
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?实现这一目标的最佳方法是什么?