-5

in java,i can use Class<? extends C> to represent a class which is a subclass of C.

es. void Test(Class<? entends C>)

But, how to implement this by cpp??

I know the cpp template,es:

template<class C>

but it can not point a subclass of some classes

R.MT
  • 1
  • 1
  • 3
    Just because the syntax looks similar doesn't mean you necessarily want a template. From your description, it could be as simple as `void Test(BaseClass& obj);` for an abstract type `BaseClass`. – juanchopanza Jun 16 '17 at 12:21
  • @juanchopanza The second answer in the recently applied duplicate answered the OP's question correctly IMO. – πάντα ῥεῖ Jun 16 '17 at 12:27
  • If I understand your correctly (I'm not Javanese), the syntax in Java means that a certain *object* must be of *any type* that is derived from a certain *base class* `C`. Correct? – Walter Jun 16 '17 at 12:33
  • @πάνταῥεῖ Really? I didn't think there was enough detail in the question to determine that. – juanchopanza Jun 16 '17 at 12:36
  • @juanchopanza Yeah, it's unclear if OP want's to have a template here at all. – πάντα ῥεῖ Jun 16 '17 at 12:37

1 Answers1

2

There are three things that come to mind.

  1. Polymorphism: simply take as function argument a reference or pointer to the base class C.

    void test(C const&obj)
    {
      /*
         manipulate the object through the public interface of C
         implemented via virtual functions
      */
    }
    
    struct D:C { /* ... */ } d;    // object of class derived from C
    test(d);
    
  2. A template using SFINAE or static_assert in combination with std::is_base_of

    template<typename T>
    std::enable_if_t<std::is_base_of<C,T>::value>
    test(T const&obj)
    { /* ... */ }
    
    template<typename T>
    void test(T const&obj)
    {
      static_assert(std::is_base_of<C,T>::value>,"T not derived from C");
      /* ... */
    }
    
  3. In the future, we may have constraints and concepts

    template<typename T>
    requires std::Derived<T,C>
    void test(T const&obj)
    {
      /* ... */
    }
    
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Walter
  • 44,150
  • 20
  • 113
  • 196