lazy_metafunction.qbk 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. [#lazy_metafunction]
  2. [section Lazy template metafunction]
  3. A ['lazy template metafunction] is a [link metafunction template metafunction]
  4. that accepts [link nullary_metafunction nullary metafunction]s as arguments,
  5. that need to be evaluated first to get the value of the argument.
  6. For example here is a `plus` metafunction for `int` values:
  7. template <class A, class B>
  8. struct plus :
  9. std::integral_constant<int, A::value + B::value>
  10. {};
  11. This metafunction takes two [link boxed_value boxed] numbers as arguments,
  12. unboxes them, adds their values and boxed the result again.
  13. It works when it is called with boxed numbers. For example:
  14. static_assert(
  15. plus<
  16. std::intgeral_constant<int, 2>,
  17. std::integral_constant<int, 2>
  18. >::type::value == 4,
  19. "This should work"
  20. );
  21. However, when it is called with a nullary metafunction returning the boxed
  22. value, it breaks:
  23. struct nullary_metafunction_returning_2
  24. {
  25. using type = std::integral_constant<int, 2>;
  26. };
  27. // Fails to compile
  28. plus<nullary_metafunction_returning_2, nullary_metafunction_returning_2>::type
  29. So `plus` is ['not] a lazy template metafunction. To make it lazy, it has to
  30. evaluate its arguments before using them:
  31. template <class A, class B>
  32. struct lazy_plus :
  33. std::integral_constant<int, A::type::value + B::type::value>
  34. {};
  35. Note that it uses `A::type::value` and `B::type::value` instead of `A::value`
  36. and `B::value`. It works when it is called with nullary metafunctions as well:
  37. static_assert(
  38. plus<
  39. nullary_metafunction_returning_2,
  40. nullary_metafunction_returning_2
  41. >::type::value == 4,
  42. "This should work"
  43. );
  44. Because it works with nullary metafunctions as arguments, it is a lazy template
  45. metafunction.
  46. [endsect]