C++ equivalent of using for a java parameter/return type

后端 未结 4 1976
慢半拍i
慢半拍i 2020-12-05 07:22

In java, to make a function that returns an object that is the same type as a parameter and extends a certain class, I would type:



        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 07:56

    Also wondered the same question, that's a C++20 approach through concepts.

    #include 
    #include 
    #include 
    using namespace std;
    
    class MyClass
    {
        public:
            inline virtual void Print() const noexcept { cout << "Myclass" << endl; }  
    };  
    
    
    class Derived : public MyClass
    {
        public:
            inline virtual void Print() const noexcept override { cout << "Derived" << endl; }  
    };  
    
    
    class NotDerived
    {};
    

    Create a concept with name CheckType which is satisfied when the concept's parameter Type is a BaseClass or a DerivedClass : BaseClass.

    template 
    concept CheckType = std::is_base_of::value;
    

    Create a generic class where the T type REQUIRES to be MyClass or Derived : MyClass type.

    template 
    requires CheckType
    class OnlyMyClass
    {
        private:
            T Instance;
    
        public:
            inline void Print() const noexcept { Instance.Print(); }    // Print
    };  
    
    
    int main()
    {
        //OnlyMyClass O1; // error, the associated constraints are not satisfied.
        OnlyMyClass    O2; // nice!
        OnlyMyClass    O3; // nice!
        O2.Print();
        O3.Print();
        
        return 0;
    }   // main
    

提交回复
热议问题