lundi 27 novembre 2017

no matching constructor for initialization of std::lock_guard

This is my c++ template class:

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);
  }
};

I can compile properly if I only call the set methods:

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"));
}

where,

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

When I call the get method:

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

I get compilation error saying:

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

But both doGet and doSet I have called using same method. Why am I getting a compilation error only when doGet runs? Is there a mistake the way I am using this?

I am compiling on MacOS 10.13.1 using:

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

Aucun commentaire:

Enregistrer un commentaire