From 73d6c73b486776d047d98460f43bcea8ec2a59f5 Mon Sep 17 00:00:00 2001 From: Lenny Maiorani Date: Fri, 15 Jan 2021 15:47:42 -0700 Subject: [PATCH] SinglyLinkedList: Correctly pass args to append, insert_before, insert_after Problem: - Using regular functions rather than function templates results in the arguments not being deduced. This then requires the same function to be written multiple times and for `move` to be used rather than `forward`. Solution: - Collapse multiple function overloads to a single function template with a deduced argument. This allows the argument to be a forwarding reference and bind to either an l-value or r-value and forward the value. --- AK/SinglyLinkedList.h | 30 +++++++++--------------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/AK/SinglyLinkedList.h b/AK/SinglyLinkedList.h index 506686f760..92d238a529 100644 --- a/AK/SinglyLinkedList.h +++ b/AK/SinglyLinkedList.h @@ -135,14 +135,10 @@ public: return value; } - void append(const T& value) + template + void append(U&& value) { - append(T(value)); - } - - void append(T&& value) - { - auto* node = new Node(move(value)); + auto* node = new Node(forward(value)); if (!m_head) { m_head = node; m_tail = node; @@ -201,14 +197,10 @@ public: delete iterator.m_node; } - void insert_before(Iterator iterator, const T& value) + template + void insert_before(Iterator iterator, U&& value) { - insert_before(iterator, T(value)); - } - - void insert_before(Iterator iterator, T&& value) - { - auto* node = new Node(move(value)); + auto* node = new Node(forward(value)); node->next = iterator.m_node; if (m_head == iterator.m_node) m_head = node; @@ -216,19 +208,15 @@ public: iterator.m_prev->next = node; } - void insert_after(Iterator iterator, const T& value) - { - insert_after(iterator, T(value)); - } - - void insert_after(Iterator iterator, T&& value) + template + void insert_after(Iterator iterator, U&& value) { if (iterator.is_end()) { append(value); return; } - auto* node = new Node(move(value)); + auto* node = new Node(forward(value)); node->next = iterator.m_node->next; iterator.m_node->next = node;