有一个类模板Foo<T>
。对于某些特定类型,函数应该使用lock_guard
. 这是示例代码:
#include <type_traits>
#include <mutex>
#include <vector>
template<typename T>
class Foo {
public:
void do_something(int k) {
if constexpr(std::is_same_v<T, NeedMutexType>) {
std::lock_guard<std::mutex> lock(mtx_);
}
resource_.push_back(k);
// code for task with resource_ ...
}
private:
std::mutex mtx_;
std::vector<int> resource_;
};
Run Code Online (Sandbox Code Playgroud)
将会std::lock_guard
在 if constexpr 范围的末尾被破坏。(如果不正确,请纠正。)
为了处理这个问题,我可以将下面的任务代码复制resource_
到 if constexpr 范围中,或者只使用原始的,std::mutex
例如mtx_.lock()
& mtx_.unlock()
。
有什么方法可以处理这个问题std::lock_guard
吗?谢谢。