CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Oct 2004
    Posts
    14

    Question Can we add two templates in c++

    Hi guys
    I have curiosity in my mind about templates.I just want to know that can we add two templates like we add two objects in c++.If we can add templates, then what is the procedure to add them.Plz tell me.

    Thanks & Regards
    Mayank Khare

  2. #2
    Join Date
    Oct 2002
    Location
    Singapore
    Posts
    3,128

    Re: Can we add two templates in c++

    If you are refering the adding two template class instances where the template parameters are the same, it will be exaclty the same as adding two normal class instances that are of the same type. If the class provides an operator+(), then addition can be performed.

  3. #3
    Join Date
    May 2004
    Location
    Norway
    Posts
    655

    Re: Can we add two templates in c++

    Additionally (no pun intended), if you template the + operator itself, you can enable addition of different template instances also. Whether or not it would make sense to do so however, depends on the context.
    Insert entertaining phrase here

  4. #4
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: Can we add two templates in c++

    You can write a template default function for operator+ which makes use of += thus:

    Code:
    template < typename L, typename R >
    L operator+( L l, const R& r )
    {
       l += r;
       return l;
    }
    The first parameter could be const L& but then you'd have to invoke the copy constructor inside the body. This way does it automatically.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured