Boost logo

Boost :

Subject: [boost] [geometry] view_as concept casting
From: Simonson, Lucanus J (lucanus.j.simonson_at_[hidden])
Date: 2009-01-07 14:32:01


There is a clear need for concept casting in a generic geometry type system. Certain geometry concepts imply that an invariant in enforced by a type that models the concept. For some types that invariant is not enforced, but may be true some of the time, and can be checked. Rather than copying the data over to a type that enforces the invariant in order to use a generic API that requires it, it is more convenient to be able to be able view the object as enforcing the invariant. For this purpose, I implemented the view_as function for conceptual casting.

//view_of can be specialized or partially specialized as needed
template <typename ConceptT, typename T>
struct view_of {
        const T& t_;
        view_of(const T& t) : t_(t) {}
        //implements an API that models ConceptT
        //in terms of T's interface
};

template <typename ConceptT, typename T>
view_of<ConceptT, T> view_as(const T& obj) {
  return view_of<ConceptT, T>(obj); }

One example of how this could be used is a polygon can be a rectangle, and if so, can be viewed as a rectangle.

if(is_rectangle(poly) && equivalent(view_as<rectangle_concept>(poly), rect))
{
        do_something_with(poly);
} else {
        do_something_else_with(poly);
}

In the above example, the equivalence check is executed only if the polygon is known to be a rectangle at run time. This is helpful, because while overloads of equivalent that accepts polygon and rectangle as well as rectangle and polygon could be implemented, as the number of types in the system grows, the number of such overloads would grow quadraticly. However, one overload that takes any object that is not a rectangle, checks at runtime if it is a rectangle and views it as a rectangle would suffice for all combinations:

template <not_rectangle_type, rectangle_type>
//concept checking boilerplate around bool return type goes here
equivalent(const not_rectangle_type& obj1, const rectangle_type& obj2) {
        return is_rectangle(obj1) &&
                equivalent(view_as<rectangle_concept(obj1), obj2);
}

Another example is that many legacy type systems will have one polygon class that doesn't enforce many invariants and is used everywhere. It depends upon the developer to know (or check) that some invariant (such as rectilinearity) is true when they use it. This polygon type cannot model rectilinear polygon concept, but needs to be conditionally viewed as rectilinear to be used with a generic API that requires type safety wrt. rectilinearity.

Is this an issue that the other geometry authors have addressed?

Regards,
Luke


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk