小编Jul*_*ian的帖子

如何在Python中编写null(无操作)上下文管理器?

有时我需要一个无效的虚拟上下文管理器.然后,它可以用作更有用但可选的上下文管理器的替身.例如:

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)

python contextmanager

32
推荐指数
3
解决办法
4204
查看次数

如何使用condition_variable真正wait_for不超过一定的持续时间

正如事实证明,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)

c++ multithreading condition-variable c++11

13
推荐指数
1
解决办法
1万
查看次数

返回const值以利用移动语义与防止诸如(a + b)= c之类的东西

我认为这个问题有点被误解了.

回归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右值引用.

所以我的问题是,我们真的不能吃蛋糕吗?(我找不到办法.)

c++ operator-overloading move-semantics c++11

7
推荐指数
1
解决办法
249
查看次数

如何忽略元组的未打包部分作为 lambda 的参数?

在 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)

有什么想法吗?实现这一目标的最佳方法是什么?

python lambda tuples argument-unpacking iterable-unpacking

6
推荐指数
2
解决办法
4894
查看次数