" , ", . : http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science). :
struct CarRetailer
{
virtual std::vector<Car*> get_cars( ) = 0;
};
, .. get_cars() , Car, . , , :
CarRetailer* ferrari = new ExpensiveCarsRetailer();
auto niceCars ferrari->get_cars();
niceCars.push_back(new Car{"Trabant"});
"promises", , , "" . , , , ++ (?) , :
struct CarRetailer
{
virtual const std::vector<const Car*> get_cars( ) = 0;
};
struct ExpensiveCarsRetailer : public CarRetailer
{
const std::vector<const ExpensiveCar*> get_cars( ) = 0;
};
(.. , , ++ 17 - ) :
struct CarRetailer
{
virtual Car* const cars_begin( ) = 0;
virtual Car* const cars_end( ) = 0;
};
struct ExpensiveCarsRetailer : public CarRetailer
{
ExpensiveCar* const cars_begin( ) override {return cars->begin();}
ExpensiveCar* const cars_end( ) override {return cars->end();}
private:
vector<ExpensiveCar>* cars;
};
(: , , , . , )
, , , ++ <algorithm> . :
any_of(dealer.cars_begin( ), dealer.cars_end( ),
[](const auto& car) -> bool {return car.hasScratch();}
) ? complain() : congratulate();
, CarDealer *cars , , , , . , , ++ . , vector<Car>*, cars_begin cars_end . , .
, , : IMHO , , .
, , , , , :
struct ExpensiveCarsRetailer /* not derived, not templated */
{
std::vector<ExpensiveCar> get_cars( ) { }
};
struct CheapCarsRetailer /* not derived, not templated */
{
std::vector<CheapCar> get_cars( );
};
:
template <typename T> print_car_table(T dealer) {
auto cars = dealer.get_cars();
for (const auto& car : cars) { std::cout << car.name() << "\t" << car.color() << "\n"; }
}
template <typename T> apply_turbo(T dealer) {
auto cars = dealer.get_cars();
for (auto& car : cars) { car.apply_turbo(); }
}
, , , . , CarMuseum, get_cars(), print_car_table(T), - . , , (class CheapDealer : public HasACarList, public HasAPriceList, /* yuck ...*/)..
, . , vector<Dealer> Dealer* ( , get_cars() ).
:
struct Car {
virtual int get_price() = 0;
virtual void apply_turbo( ) = 0;
};
struct CheapCar: public Car
{
int get_price( ) {}
void apply_turbo( ){throw OperationNonSupportedException();};
};
++, ? , , , . .
, , Scala ( ) . , , .