Templates for member functions

This is a discussion on Templates for member functions within the C++ Programming forums, part of the General Programming Boards category; Hello, Can i make only one member function of a class generic using templates. Code: class A { int member; ...

  1. #1
    Registered User
    Join Date
    Jul 2005
    Posts
    1

    Templates for member functions

    Hello,
    Can i make only one member function of a class generic using templates.
    Code:
       class A
       {
          int member;
          
        void func1()
        {
    
         }
      
         template<class T>
    
       void func2(T& obj);
      
        };
    
     template<class T>
      void A:: func2(T& obj)
      {
         obj.val=0;
     }

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,310
    Yes. There are some conditions on being allowed to do that (eg such a function cannot be virtual, IIRC).

    In your example, you might also want to use a predicate to ensure that type T has a member named val that can be set to zero, rather than just waiting until you use A::func2() on an object of arbitrary type. I'll leave researching that suggestion as a learning exercise.....

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Is it legal to have functions within functions?
    By Programmer_P in forum C++ Programming
    Replies: 13
    Last Post: 05-25-2009, 11:21 PM
  2. templates and inheritance problem
    By kuhnmi in forum C++ Programming
    Replies: 4
    Last Post: 06-14-2004, 02:46 AM
  3. Factory Functions HOWTO
    By GuardianDevil in forum Windows Programming
    Replies: 1
    Last Post: 05-01-2004, 01:41 PM
  4. im extreamly new help
    By rigo305 in forum C++ Programming
    Replies: 27
    Last Post: 04-23-2004, 11:22 PM
  5. Shell functions on Win XP
    By geek@02 in forum Windows Programming
    Replies: 6
    Last Post: 04-19-2004, 05:39 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21