manpagez: man pages & more
info ginac
Home | html | info | man
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.4.4 Subexpressions

Our scalar product class has two subexpressions: the left and right operands. It might be a good idea to make them accessible via the standard nops() and op() methods:

 
size_t sprod::nops() const
{
    return 2;
}

ex sprod::op(size_t i) const
{
    switch (i) {
    case 0:
        return get_struct().left;
    case 1:
        return get_struct().right;
    default:
        throw std::range_error("sprod::op(): no such operand");
    }
}

Implementing nops() and op() for container types such as sprod has two other nice side effects:

There is a non-const variant of op() called let_op() that allows replacing subexpressions:

 
ex & sprod::let_op(size_t i)
{
    // every non-const member function must call this
    ensure_if_modifiable();

    switch (i) {
    case 0:
        return get_struct().left;
    case 1:
        return get_struct().right;
    default:
        throw std::range_error("sprod::let_op(): no such operand");
    }
}

Once we have provided let_op() we also get subs() and map() for free. In fact, every container class that returns a non-null nops() value must either implement let_op() or provide custom implementations of subs() and map().

In turn, the availability of map() enables the recursive behavior of a couple of other default method implementations, in particular evalf(), evalm(), normal(), diff() and expand(). Although we probably want to provide our own version of expand() for scalar products that turns expressions like ‘<a+b|c>’ into ‘<a|c>+<b|c>’. This is left as an exercise for the reader.

The structure<T> template defines many more member functions that you can override by specialization to customize the behavior of your structures. You are referred to the next section for a description of some of these (especially eval()). There is, however, one topic that shall be addressed here, as it demonstrates one peculiarity of the structure<T> template: archiving.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]
© manpagez.com 2000-2024
Individual documents may contain additional copyright information.