Thread: about template and friend function

  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    25

    about template and friend function

    What to do with friend functions of a class under template?

  2. #2
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    easiest way is to define the friend function within the template

    to use the canonical example of op <<
    Code:
    template <typename T>
    class SomeTemplate
    {
    private:
    	T m_t;
    public:
    	// some methods
    
    	friend std::ostream &operator>>(std::ostream &os, const SomeTemplate<T> &inst)
    	{
    		os >> inst.m_t;
    		return os;
    	}
    };
    of course, this isn't really cool if you want to use the same friend function for multiple templates.
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    25
    What's the difference between a friend function declared within the class and one declared outside the class?

  4. #4

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Function template has already been defined
    By Elysia in forum C++ Programming
    Replies: 19
    Last Post: 04-14-2009, 10:17 AM
  2. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  3. Replies: 8
    Last Post: 07-24-2006, 08:14 AM
  4. Declare a template class as a friend?
    By AH_Tze in forum C++ Programming
    Replies: 11
    Last Post: 05-19-2004, 09:24 PM
  5. oh me oh my hash maps up the wazoo
    By DarkDays in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2001, 12:54 PM