mirror of
https://github.com/ultimatepp/ultimatepp.git
synced 2026-05-15 14:16:07 -06:00
New Core Tutorial
git-svn-id: svn://ultimatepp.org/upp/trunk@10538 f0d560ea-af0d-0410-9eb7-867de7ffcac7
This commit is contained in:
parent
dd88feaf2e
commit
6c22e727de
37 changed files with 3125 additions and 0 deletions
55
tutorial/CoreTutorial/PolyArray.cpp
Normal file
55
tutorial/CoreTutorial/PolyArray.cpp
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
#include "Tutorial.h"
|
||||
|
||||
void PolyArray()
|
||||
{
|
||||
/// .Polymorphic `Array`
|
||||
|
||||
/// `Array` can even be used for storing polymorphic elements:
|
||||
|
||||
struct Number {
|
||||
virtual double Get() const = 0;
|
||||
String ToString() const { return AsString(Get()); }
|
||||
virtual ~Number() {}
|
||||
};
|
||||
|
||||
struct Integer : public Number {
|
||||
int n;
|
||||
virtual double Get() const { return n; }
|
||||
};
|
||||
|
||||
struct Double : public Number {
|
||||
double n;
|
||||
virtual double Get() const { return n; }
|
||||
};
|
||||
|
||||
/// To add such derived types to `Array`, you can best use in-place creation with `Create`
|
||||
/// method:
|
||||
|
||||
Array<Number> num;
|
||||
num.Create<Double>().n = 15.5;
|
||||
num.Create<Integer>().n = 3;
|
||||
|
||||
DUMP(num);
|
||||
|
||||
/// Alternatively, you can use `Add(T *)` method and provide a pointer to the newly created
|
||||
/// instance on the heap (`Add` returns a reference to the instance):
|
||||
|
||||
Double *nd = new Double;
|
||||
nd->n = 1.1;
|
||||
num.Add(nd);
|
||||
|
||||
DUMP(num);
|
||||
|
||||
/// Array takes ownership of heap object and deletes it as appropriate. We recommend to use
|
||||
/// this variant only if in-place creation with `Create` is not possible.
|
||||
|
||||
/// It is OK do directly apply U++ algorithms on `Array` (the most stringent requirement of
|
||||
/// any of basic algorithms is that there is `IterSwap` provided for container iterators
|
||||
/// and that is specialized for `Array` iterators):
|
||||
|
||||
Sort(num, [](const Number& a, const Number& b) { return a.Get() < b.Get(); });
|
||||
|
||||
DUMP(num);
|
||||
|
||||
///
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue