Code Template Parameters

One cannot provide a function pointer as a template argument. This means that cases in which polymorphism is desirable for compile-time reasons (such as using one set of operations when testing and another set of operations when running the code), or where the behavior of code depends on a compile-time element and should be able to evolve in an open-closed fashion, cannot be handled by passing the correct function pointer.

Of course, a common trick in template metaprogramming is to replace entities which cannot be used as parameters (such as non-integer values) with types that have the entities as static members.

template <typename T>
void Frobnicate(int value) { T::Process(value); } 

struct Print
{ static void Process(int value) { std::cout << value; } }; 

struct Ignore
{ static void Process(int) {} }; 

Frobnicate<Print>(10);
Frobnicate<Ignore>(10);

As long as the structure that contains the function has external linkage (that is, it’s not defined inside a function) this will work and inject the correct kind of behavior into the function template at compile-time, possibly also performing any required inlining.

A typical application of this approach is, as mentioned earlier, unit testing: when working with rendering-related or input-related objects, it’s useful to replace their primitives with mocks that can test if the calls performed were those expected. This replacement can be done with runtime polymorphism (using an interface for the primitives, with a real class and a mock class boh implementing it) but leads to unnecessary performance loss (the overhead of runtime polymorphism that is not really required outside of the unit testing scenario). Using compile-time polymorphism based on templates, unit testing works, but the runtime code is still as optimised as if no unit testing ever happened.

0 Responses to “Code Template Parameters”


  1. No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



1150 feed subscribers
(readers who polled a feed this week)