How can I make this code to be a template?

Here is the code:

1
2
3
4
  doublyLinkedList& doublyLinkedList::operator<<(const int value)
{ insert.first(value);
return *this;
}


I have been trying and trying but I keep getting errors
Surely you can give us more information than that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Example program
#include <iostream>
#include <string>

template <typename T>
class insert_object {
  public:
    void first(T value)
    {
        std::cout << "insert.first(" << value << ") called \n";
    }
};

template <typename T>
class doublyLinkedList {
  public:
    doublyLinkedList& operator<<(const T& value);
    
    insert_object<T> insert; // just to make it compile, no idea what you intend
};

template <typename T>
doublyLinkedList<T>& doublyLinkedList<T>::operator<<(const T& value)
{
    insert.first(value);
    return *this;
}

int main()
{
    using std::string;
    
    doublyLinkedList<int> list;
    list << 3 << 2;
    
    doublyLinkedList<string> str_list;
    str_list << "hello" << " there";
    str_list << "another " << "happy " << "landing";
}
Last edited on
Here is my code:
1
2
3
4
5
6
template<class Type>
doublyLinkedList<Type>& doublyLinkedList<Type>::operator<<(const Type& info)
{
     insertNode(info);
     return *this;
}

I get this error:
out-of-line definition of operator<<
does not match any declaration in doublyLinkedList<Type>
Show how you declare it in your class definition.

Also... are you putting the implementation code in a separate ".cpp" file, separate from the header file? Because that can cause problems for templates.
Last edited on
This is how it is declared:
 
  friend ostream& operator<<(ostream& , const doublyLinkedList<Type>&);
That is a completely different function though... Your original function involves no ostreams.

If it's a friend function, then it isn't a class member.
You have to do something odd like this...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Example program
#include <iostream>
#include <string>

template <typename T>
class insert_object { };

template <typename Type>
class doublyLinkedList {

    template <typename FriendListType>
    friend std::ostream& operator<<(std::ostream& , const doublyLinkedList<FriendListType>&);

  private:
    insert_object<Type> insert; // just to make it compile, no idea what you intend
};

template <typename Type>
std::ostream& operator<<(std::ostream& os, const doublyLinkedList<Type>& list)
{
    os << "Hello there!";
    list.insert; // insert is private, so this test makes sure it's a friend
    return os;
}

int main()
{
    using std::string;
    
    doublyLinkedList<int> list;
    
    std::cout << list << '\n'; // this will use the << operator
}

Last edited on
Topic archived. No new replies allowed.