I want to realize a singly linked list with C++ and Templates. Therefore I already wrote a Header file (list.h):
list.h
#ifndef LINKEDLIST_LIST_H
#define LINKEDLIST_LIST_H
#include <iostream>
#include <string>
#include <tuple>
#include <functional>
template<typename K, typename V>
class list;
template<typename K, typename V>
list<K, V> &operator+=(list<K, V> &, const std::tuple<K, V>);
template<typename K, typename V>
list<K, V> &operator-=(list<K, V> &, const K);
template<typename K, typename V>
std::ostream &operator<<(std::ostream &, const list<K, V> &);
template<typename K, typename V>
class list {
private:
struct element {
const K key;
const V value;
element *next;
element(const std::tuple<K, V>, element *);
};
element *head = nullptr;
public:
~list();
const V *search(const K) const;
bool isEmpty() const;
bool isSorted(std::function<bool(K, K)> lessThan) const;
std::tuple<K, V> popHead();
void sort(std::function<bool(K, K)> lessThan);
friend list<K, V> &operator+=<>(list<K, V> &, const std::tuple<K, V>);
friend list<K, V> &operator-=<>(list<K, V> &, const K);
friend std::ostream &operator<<<>(std::ostream &, const list<K, V> &);
};
#endif //LINKEDLIST_LIST_H
One should be able to add elements to the list via a += operator overloading. But when I try to implement the method I get a "expected type-specifier" error from my compiler. This happens when trying to compile:
element *newElement = new element(tuple, current);
list.cpp (+= Operator Overloading)
template<typename K, typename V>
list<K, V> &operator+=(list<K, V> &list, const std::tuple<K, V> tuple) {
// Iterate over the list to check if the key already exists.
auto current = list.head;
while (current != nullptr) {
if (current->value == std::get<0>(tuple)) {
V *oldValue = current->value;
current->value = std::get<1>(tuple);
delete oldValue; // Cleanup old value.
return list;
}
}
// Current is now the last element.
element *newElement = new element(tuple, current);
// Update head in case it is not set already.
if (head == nullptr) {
head = newElement;
}
};
How can I (is this even possible) created generic instances of element inside a generic function?