diff --git a/crdt.hpp b/crdt.hpp index fde7aab..5ee10b7 100644 --- a/crdt.hpp +++ b/crdt.hpp @@ -35,6 +35,24 @@ using CrdtNodeId = uint64_t; #include #include +// Add this helper struct at the beginning of the file, outside of the CRDT class + +// Helper struct to check if a container has emplace_back method +template struct has_emplace_back : std::false_type {}; + +template +struct has_emplace_back().emplace_back(std::declval()))>> + : std::true_type {}; + +// Helper function to add an element to a container +template void add_to_container(Container &container, Element &&element) { + if constexpr (has_emplace_back::value) { + container.emplace_back(std::forward(element)); + } else { + container.emplace(std::forward(element)); + } +} + /// Represents a single change in the CRDT. template struct Change { K record_id; @@ -298,8 +316,7 @@ class CRDT : public std::enable_shared_from_this - constexpr void insert_or_update(const K &record_id, Pairs &&...pairs) { + template constexpr void insert_or_update(const K &record_id, Pairs &&...pairs) { insert_or_update_impl>>(record_id, nullptr, std::forward(pairs)...); } @@ -324,9 +341,7 @@ class CRDT : public std::enable_shared_from_this>>(record_id, nullptr); - } + void delete_record(const K &record_id) { delete_record_impl>>(record_id, nullptr); } /// Deletes a record by marking it as tombstoned, and stores the change. /// @@ -336,8 +351,7 @@ class CRDT : public std::enable_shared_from_this - void delete_record(const K &record_id, ChangeContainer &changes) { + template void delete_record(const K &record_id, ChangeContainer &changes) { delete_record_impl(record_id, &changes); } @@ -923,7 +937,7 @@ class CRDT : public std::enable_shared_from_thisinsert(changes->end(), Change(record_id, col_name, value, col_version, db_version, node_id_, db_version)); + add_to_container(*changes, Change(record_id, col_name, value, col_version, db_version, node_id_, db_version)); } }; @@ -932,8 +946,7 @@ class CRDT : public std::enable_shared_from_this - void delete_record_impl(const K &record_id, ChangeContainer *changes) { + template void delete_record_impl(const K &record_id, ChangeContainer *changes) { if (is_record_tombstoned(record_id)) { return; } @@ -952,7 +965,7 @@ class CRDT : public std::enable_shared_from_this(CrdtMap(), std::move(deletion_clock))); if (changes) { - changes->insert(changes->end(), Change(record_id, std::nullopt, std::nullopt, 1, db_version, node_id_, db_version)); + add_to_container(*changes, Change(record_id, std::nullopt, std::nullopt, 1, db_version, node_id_, db_version)); } } };