Thread: Can you use template with struct?

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    5

    Can you use template with struct?

    If I have this,

    Code:
    struct BinTreeNode
    {
        int data;
        BinTreeNode * left;
        BinTreeNode * right;
    };
    could I make it in a template?

    I tried doing this,

    Code:
    template <struct T>
    struct BinTreeNode
    {
        T data;
        BinTreeNode * left;
        BinTreeNode * right;
    };
    but it gives me errors.

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    No, you can not use the struct keyword there.

    However, the class keyword doesn't mean that T can only be a class. It can be any type. The synonym for class is typename in this context.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    I actually prefer to use typename in all cases to avoid ambiguity. I've encountered a few situations where the class keyword actually caused problems, although I can't remember the specifics at the moment.

  4. #4
    Registered User
    Join Date
    Aug 2008
    Location
    Belgrade, Serbia
    Posts
    163
    I've read somewhere that typename actually has some advantages and even if it didn't I would still use it because it's just so much clearer.
    Vanity of vanities, saith the Preacher, vanity of vanities; all is vanity.
    What profit hath a man of all his labour which he taketh under the sun?
    All the rivers run into the sea; yet the sea is not full; unto the place from whence the rivers come, thither they return again.
    For in much wisdom is much grief: and he that increaseth knowledge increaseth sorrow.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 04-06-2011, 01:37 PM
  2. Replies: 3
    Last Post: 01-30-2011, 04:28 PM
  3. template parameter on a function that dont use the template
    By underthesun in forum C++ Programming
    Replies: 1
    Last Post: 06-22-2009, 05:38 PM
  4. Specialising a member function with a template template parameter
    By the4thamigo_uk in forum C++ Programming
    Replies: 10
    Last Post: 10-12-2007, 04:37 AM
  5. Replies: 4
    Last Post: 11-01-2006, 02:23 PM