Graphics Reference
In-Depth Information
Listing 37.5: A C++ trait for exposing axis-aligned bounding box, sphere, and
point keys from primitives.
1
2
3
4
5
6
7
8
9
10
template < class Value >
class PrimitiveKeyTrait {
public :
static void getBoxBounds ( const Value & primitive, AABox& bounds);
static void getBallBounds ( const Value & primitive, Ball & bounds);
static void getPosition ( const Value & primitive, Point3 & pos);
static bool intersectsBox ( const Value & primitive, const AABox& box);
static bool intersectsBall( const Value & primitive, const Ball & ball);
static bool findFirstRayIntersection( const Value & primitive, const Ray & ray,
float & distance);
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
};
template <>
class PrimitiveKeyTrait< Triangle >{
public :
static void getBoxBounds( const Triangle & tri, AABox& bounds) {
bounds = AABox(min(tri.vertex(0), tri.vertex(1), tri.vertex(2)),
max(tri.vertex(0), tri.vertex(1), tri.vertex(2)));
}
...
};
template < class Value , class Bounds = PrimitiveKeyTrait< Value >>
class SomeStructure {
...
void insert( const Value & value) {
Box key;
Bounds< Value >::getBoxBounds(value, key);
...
}
};
Overloaded functions are a viable alternative to partial template specialization
in languages that support them. An example of providing an interface through
overloading in C++ is shown in Listing 37.6. This is similar to the template spe-
cialization, but is a bit more prone to misuse because some languages (notably
C++) dispatch on the compile-time type instead of the runtime type of an object.
(ML is an example of a language that dispatches on runtime type.) If mixed with
inheritance, overloading can thus lead to semantic errors.
Listing 37.6: A C++ trait implemented with overloading instead of templates.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void getBoxBounds( const Triangle & primitive, AABox& bounds) { ... }
void getBoxBounds( const Ball & primitive, AABox& bounds) { ... }
void getBoxBounds( const Mesh& primitive, AABox& bounds) { ... }
...
template < class Value >
class SomeStructure {
...
void insert( const Value & value) {
Box key;
// Automatically finds the closest overload
getBoxBounds(value, key);
...
}
};
 
Search WWH ::




Custom Search