Java c++;实施;类别<;?恩滕斯C>&引用;

Java c++;实施;类别<;?恩滕斯C>&引用;,java,c++,Java,C++,在java中,我可以使用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 fr

在java中,我可以使用
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);
    
  • 使用或结合使用
    模板

    模板
    std::如果启用,则启用
    测试(T常数和obj)
    { /* ... */ }
    模板
    无效试验(T常数和obj)
    {
    静态断言(std::is of::value>,“T不是从C派生的”);
    /* ... */
    }
    
  • 将来,我们可能会

    模板
    需要std::派生
    无效试验(T常数和obj)
    {
    /* ... */
    }
    

  • 语法看起来很相似并不意味着您一定需要一个模板。根据您的描述,它可以像
    void测试(BaseClass&obj)一样简单
    对于抽象类型
    基类
    @juanchopanza,最近应用的副本中的第二个答案在我看来正确地回答了OP的问题。如果我正确理解了您的问题(我不是爪哇人),Java中的语法意味着某个对象必须是从某个基类
    C
    派生的任何类型。正确吗?@πνταῥεῖ 真正地我认为问题中没有足够的细节来确定这一点。@juanchopanza是的,不清楚OP是否希望在这里有一个模板。非常感谢
    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");
      /* ... */
    }
    
    template<typename T>
    requires std::Derived<T,C>
    void test(T const&obj)
    {
      /* ... */
    }