template paramters: example from Modern C++ Design

504 Views Asked by At

I have read "Modern C++ Design"
and I have a question in its sample code

in p278 p279
or refer to Loki's source if you don't have the book
BasicDipatcher::Add and BasicDispatcher::Go in MutilMethods.h

in page p278 bottom to p279 up
it has a piece of sample code

typedef BasicDispatcher<Shape> Dispatcher;
void HatchRectanglePoly(Shape& lhs, Shape& rhs) {...}
Dispatcher disp;
disp.Add<Rectangle, Poly>(HatchRectanglePoly);

I found in function Go, its arguments are BaseLhs&, BaseRhs&
which in this case, should be Shape&, Shape&

and in function Add, its arguments are SomeLhs&, SomeLhs&,
which in this case, should be Rectangle&, Poly&

so the key won't match anyway because they are different

therefore the callback(HatchRectanglePoly) won't be called
(If I add disp.Go.... in the samele code),
and instead, a std:runtime_error will be thrown

Am i correct??

thanks

1

There are 1 best solutions below

0
DDMC On

The BaseLhs and BaseRhs are template parameters. Just like function parameter, the actual value will be provided when you use it (instantiate the template), not when you define it.

template
<
  class BaseLhs,
  class BaseRhs = BaseLhs,
  typename ResultType = void,
  typename CallbackType = ResultType (*)(BaseLhs&, BaseRhs&)
>
class BasicDispatcher

By default, BaseRhs is the same as BaseLhs.

typedef BasicDispatcher<Shape> Dispatcher;
Dispatcher disp;

Here, we instantiate a version of BasicDispatcher, the BaseLhs is Shape, the BaseRhs is Shape too (since we provide only 1 template argument). In this instantiation, the Go method is somewhat like this:

void Go(Shape& lhs, Shape& rhs);

The same goes for Add.

In short: The type name written in template<...> is just a placeholder, it will be substituted by actual type when use.

Hope you find this helpful.

P.S: About the class and typename inside the angle bracket, they have the same meaning, I guess it's just a hint to the reader that BaseLhs and BaseRhs will always be classes.