How do I define a function in a class template?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tomás

    #1

    How do I define a function in a class template?


    template <class T>
    class Monkey {

    int Eat();
    };

    int Monkey::Eat()
    {
    return 5;
    }


    This won't compile. In what way have I defined the function wrongly? Are
    you supposed to write them like this?:

    template <class T>
    class Monkey {

    int Eat();
    };

    template <class T>
    int Monkey<T>::Eat( )
    {
    return 5;
    }


    It seems a bit pedantic to me that you have to that...

    -Tomás
  • Tomás

    #2
    Re: How do I define a function in a class template?

    [color=blue]
    > It seems a bit pedantic to me that you have to that...[/color]


    Opps I read over my post there and it sounded like I was being sarcastic.

    Really, I want to know how to do this properly.

    I'll have to get Bjarne's book out of the library again... I used to know
    all this stuff about a year ago!

    Any help appreciated.

    -Tomás

    Comment

    • Victor Bazarov

      #3
      Re: How do I define a function in a class template?

      Tomás wrote:[color=blue][color=green]
      >>It seems a bit pedantic to me that you have to that...[/color]
      >
      >
      >
      > Opps I read over my post there and it sounded like I was being sarcastic.
      >
      > Really, I want to know how to do this properly.
      >
      > I'll have to get Bjarne's book out of the library again... I used to know
      > all this stuff about a year ago![/color]

      You did it right. Your 'Eat' member is _private_ in your class template
      'Monkey', so it cannot be used by anybody.

      V
      --
      Please remove capital As from my address when replying by mail

      Comment

      • osmium

        #4
        Re: How do I define a function in a class template?

        "Tomás" writes:
        [color=blue][color=green]
        >> It seems a bit pedantic to me that you have to that...[/color]
        >
        >
        > Opps I read over my post there and it sounded like I was being sarcastic.
        >
        > Really, I want to know how to do this properly.
        >
        > I'll have to get Bjarne's book out of the library again... I used to know
        > all this stuff about a year ago!
        >
        > Any help appreciated.[/color]

        Help doing what? You have a compiler, do you not? Why not try the second
        way? If there are problems fix them.. Try adding public:. It not only
        looks right, it works for me. What more do you want?


        Comment

        Working...