这是我的 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_);
但是 doGet
和 doSet
我都使用相同的方法调用了。为什么仅当 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/