c++ - 没有用于初始化 std::lock_guard<std::mutex> 的匹配构造函数

标签 c++ c++11 locking mutex variadic-templates

这是我的 C++ 模板类:

template <class Type, class Key = ColumnKey>
class Column {
protected:
  std::shared_ptr<Type> doGet() const {
    std::lock_guard<std::mutex> lock(mutex_);
    return std::make_shared<Type>(value_);
  }
  void doSet(const std::shared_ptr<Type> &value) {
    std::lock_guard<std::mutex> lock(mutex_);
    value_ = *value;
  }
private:
  Type value_;
  std::mutex mutex_;
};

template<class... Columns>
class Table : private Columns... {
public:
  template<class Type, class Key = ColumnKey>
  std::shared_ptr<Type> get() {
    return Column<Type, Key>::doGet();
  }

  template<class Type, class Key = ColumnKey>
  void set(const std::shared_ptr<Type> &value) {
    Column<Type, Key>::doSet(value);
  }
};

如果我只调用 set 方法,我可以正确编译:

int main() {
  Table3 table3;
  table3.set<int>(std::make_shared<int>(1));
  table3.set<std::string, Key1>(std::make_shared<std::string>("hello_3a"));
  table3.set<std::string, Key2>(std::make_shared<std::string>("hello_3b"));
}

在哪里,

struct Key1;
struct Key2;
using Table3 = Table<Column<int>, Column<std::string, Key1>, Column<std::string, Key2>>;

当我调用 get 方法时:

std::cout<<*table3.get<int>()<<std::endl;
std::cout<<*table3.get<std::string, Key1>()<<std::endl;

我收到编译错误:

error: no matching constructor for initialization of 'std::lock_guard' std::lock_guard lock(mutex_);

但是 doGetdoSet 我都使用相同的方法调用了。为什么仅当 doGet 运行时我才收到编译错误?我使用它的方式有误吗?

我在 MacOS 10.13.1 上编译使用:

g++ file.cpp -std=c++11 -o file

最佳答案

doGet() 是一个const 函数。

如下声明mutex:

mutable std::mutex mutex_;

建议: 使用 std::scoped_lock 而不是 std::lock_guard

快乐编码!!! 干杯!!!

关于c++ - 没有用于初始化 std::lock_guard<std::mutex> 的匹配构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47519972/

相关文章:

c++ - 向更新其物理状态的对象添加数值积分

c++ - 如何在写入其他 std::atomic 之后强制读取 std::atomic?

c++ - 为什么 std::async 比简单的分离线程慢?

c++ - 返回 protected 数据时如何使用 lock_guard

使用 get/set 的 C# 线程安全

php - 多用户应用程序记录锁定 - 最佳方法?

c++ - nullptr 的运算符 <<(流输出)

c++ - 使用具有捕获值的 lambda 对容器进行排序

c++ - while 循环没有正确终止

c++ - std::initializer_list<int>({1,2,3}) 和 {1,2,3} 有什么区别?