Visit the LQ Articles and Editorials section
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 03-28-2011, 08:42 PM   #1
Registered: May 2009
Distribution: Debian wheezy
Posts: 250

Rep: Reputation: 31
How to write a stream inserter for a template class

I had some trouble doing this but finally figured it out. Here is a general solution:
#include <iostream>
using namespace std;

// Pre-declare class template...
template <class T> class MyTemplate;

// So we can pre-declare inserter...
template <class T> ostream &operator<<(ostream &stream, const MyTemplate<T> &t);

// So when we define the class template...
template <class T> class MyTemplate {
    // We can declare inserter a friend.
    friend ostream &operator<< <T> (ostream &stream, const MyTemplate<T> &t);

// Now inserter can access MyTemplate's private members
template <class T> ostream &operator<<(ostream &stream, const MyTemplate<T> &t) {
Hope this helps someone.
Old 03-31-2011, 02:56 AM   #2
LQ Guru
Registered: May 2009
Location: Gibraltar, Gibraltar
Distribution: Fedora 20 with Awesome WM
Posts: 6,805
Blog Entries: 1

Rep: Reputation: 1295Reputation: 1295Reputation: 1295Reputation: 1295Reputation: 1295Reputation: 1295Reputation: 1295Reputation: 1295Reputation: 1295

Thanks for sharing your solution. Off the Zero Reply List.

Kind regards,



c++, ostream, template

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
dynamic template class erat123 Programming 1 06-20-2007 02:10 PM
c++ class template doesn't work!! tagigogo Programming 2 11-02-2005 05:45 PM
Template class with a template member... Nicholas Bishop Programming 3 02-21-2005 09:27 PM
template class ckcheung0927 Programming 3 11-28-2004 04:59 PM
C++ template class syntax rong Programming 12 08-13-2003 01:26 PM

All times are GMT -5. The time now is 03:32 AM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration