generic <T extends base> equivalent in c++?

Discussion in 'Programming & Software Development' started by MadOnion87, May 31, 2008.

  1. MadOnion87

    MadOnion87 Member

    Joined:
    Jul 10, 2002
    Messages:
    3,232
    Location:
    Old Trafford, Manchester
    hello all

    I'm wondering if there is an equivalent of java's class class_name<T extends b> in c++?
    I know generics and templates are different but I'm trying to enforce that the given class extends b (because I'm using functions in b) and I want it to freely return T by methods inside class_name.

    [edit] or if I can make sure that T implements an interface so that I can call a particular method [/edit]

    thanks
     
    Last edited: May 31, 2008
  2. bugayev

    bugayev Whammy!

    Joined:
    May 15, 2003
    Messages:
    4,092
    Location:
    Melbourne
  3. Bradzac

    Bradzac Member

    Joined:
    Aug 17, 2003
    Messages:
    1,744
    From memory, c++ doesnt support all the functionality you get with generics, instead you use the STL (Standard Template Library).

    Edit: Unless you are using c++.NET
     
    Last edited: May 31, 2008
  4. OP
    OP
    MadOnion87

    MadOnion87 Member

    Joined:
    Jul 10, 2002
    Messages:
    3,232
    Location:
    Old Trafford, Manchester
    yea i'm using inheritance, but I also want to template with inheritance. For example, I have:
    Code:
    class A {
        public:
            virtual int method1();
    };
    
    template <class T> class B {
    // something that need to use A::method1 here
    // therefore T must be a derived class of A
    // but I don't know how to enforce this in c++
    };
    
    so yea, its something like that. I don't have to use template I guess, but I need to make sure the class that I'm operating on has an implementation of method1.
    If this was in java then I would have done class B<T implements Method1_Interface> {...}

    [edit] and no I'm not using c++.net [/edit]
     
  5. Ravenclaw

    Ravenclaw Member

    Joined:
    Dec 6, 2004
    Messages:
    2,090
    madonion:

    i don't think you really need to worry. if someone substitutes in the wrong class they will get an error when the template is instantiated. might want to check out boost concept checking.
     
  6. OP
    OP
    MadOnion87

    MadOnion87 Member

    Joined:
    Jul 10, 2002
    Messages:
    3,232
    Location:
    Old Trafford, Manchester
    indeed I was worrying too much lol
    just tried it and it works (I don't really need to enforce it)

    thanks
     

Share This Page

Advertisement: