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

后端 未结 4 1983
慢半拍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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 08:14

    We can use enable_if here if you have C++11 or higher available to you

    template::value>::type* = nullptr>
    T Foo(T bar)
    {
        return T();
    }
    

    For example:

    class MyClass
    {
    public:
        int a = 1;
    };
    
    class Derived : public MyClass
    {
    public:
        int b = 2;
    };
    
    class NotDerived
    {
    public:
        int b = 3;
    };
    
    template::value>::type* = nullptr>
    T Foo(T bar)
    {
        return T();
    }
    
    int main()
    {
        Derived d;
        NotDerived nd;
        std::cout << Foo(d).b << std::endl;; // works
        //std::cout << (Foo(nd)).b << std::endl;; //compiler error
    
        return 0;
    }
    

    Live Demo

提交回复
热议问题