Lecture Notes for Advanced Programming II

6 May 2004 - Expression Templates


Outline


Function Arguments


The No-Lambda Problem


Template Metaprogramming


Run-Time Expression Evaluation


The Interpreter Pattern


The Interpreter Abstract Classes


The Interpreter Leaf Classes


Using The Interpreter Classes


From Run Time to Compile Time


Abstracting Interpreter Classes


Template Interpreter Expression Classes


Template Interpreter Nilary Classes


Using Template Interpreter Classes


Unpacking the Beast

binary_expression

  <binary_expression
     <variable, literal, std::less<rtype> >,

   binary_expression
     <literal, variable, std::less<rtype> >,

   std::logical_or<result_type> 
  >

  (binary_expression
     <variable, 
      literal, 
      std::less<result_type> 
     >
     (variable(t), literal(97.6)), 

   binary_expression
     <literal,
      variable,
      std::less<result_type> 
     >
     (literal(99.6), variable(t)
  )  


Compile-Time Evaluation


Helper Template Functions


Helper Template Function Example


Overloaded Helper Template Functions


Variables


Literals


Literal Conversions


Type Mapping


Mapping POD Types


Type Mapping Example


Using Type Representations


Type Representation Mapping Example


Traits


Expression Template Arguments


Expression Template Argument Example

$ cat et-lambda.cc
template < class Expression >
static result_type
find_max(Expression expr, 
  double l, double r, double s)

  result_type mx = expr.evaluate(l)
  while l < r
    mx = std::max(expr.evaluate(l), mx)
    l += s
  return mx


int main()
  variable x
  std::cout 
    << find_max((x - 3)*(x - 5), 1, 10, 1)
    << "\n"
    << find_max((x - 3)/(x + 5), 1, 10, 1)
    << "\n"

$ g++ -o et-lambda et-lambda.cc

$ ./et-lambda
24
0.428571

$ 

See the complete code.


Callable Expression Templates


Callable Expression Templates Example

 
$ cat et-callable.cc 
template <class Temps> 
static unsigned
abnormal_count(const Temps & temps) 
  variable t 
  return 
    std::count_if(
      temps.begin(), temps.end(), 
      (t < 97.6) || (99.6 < t))


int main() 
  double temps[] = 
    { 95, 96, 97, 98, 99, 100, 101} 
  std::vector t(temps, temps + 7)

  std::cout << abnormal_count(t) 
            << " abnormal temperatures.\n"

$ g++ -o et-callable et-callable.cc

$ ./et-callable
5 abnormal temperatures.

$

See the complete code.


Points to Remember


Bibliography


This page last modified on 6 May 2004.