返回不同的类型

Returning different types

本文关键字:类型 返回      更新时间:2023-10-16

如何(在运行时)决定从函数返回哪种类型
这可能吗
我想是的,但人们永远无法确定。

如果可以选择使用Boost,请考虑使用Boost.Variant。

你可以把变体想象成类固醇上的union。它适用于大多数C++类型,并允许编译时和运行时多态性,但它不需要类型的公共基类。主要的缺点是它涉及大量的模板元编程,因此会给编译器带来一些负载。

这里有一个简短的例子来获得这个想法:

 typedef boost::variant<float, std::string> MyVariant;
 MyVariant GetInt() { return MyVariant(42); }
 MyVariant GetString() { return MyVariant("foo"); }
 MyVariant v;
 //run-time polymorphism:
 int number = boost::get<int>(v);   // this line may throw (basically a dynamic_cast)
 //compile time polymorphism:
 boost::apply_visitor(Visitor(), v);  
 // where Visitor is a functor overloading operator() for *all* types in the variant

一个更轻量级的替代方案是Boost。任何,请参阅此页面进行比较。

使用多态性

public interface MyType {
    public void doSomething();
}
public class A implements MyType {
    public void doSomething(){}
}
public class B implements MyType {
    public void doSomething(){}
}
public class MyClass {
    public MyType getData(){
        if ( /* some condition */ ){ return new A(); } 
        return new B();
    }
    public void test(){
        MyType o = this.getData();
        o.doSomething();
    }
}

则简单地返回类型为CCD_ 2并直接在该对象上调用CCD_;即您不需要知道返回的类型是A还是B。您所关心的只是它实现了doSomething。这就是多态性的美妙之处,即不再有丑陋的isgetTypeinstanceOf(Java)等。