Quick Links:

bal | bbl | bdl | bsl

Namespaces

Component bslmf_metaint
[Package bslmf]

Provide a meta-function to map integral constants to unique types. More...

Namespaces

namespace  bslmf

Detailed Description

Outline
Purpose:
Provide a meta-function to map integral constants to unique types.
Deprecated:
Use bslmf_integralconstant instead.
Classes:
bslmf::MetaInt meta-function mapping integral constants to C++ types
Description:
This component defines a simple template structure used to map an integral constant to a C++ type. bslmf::MetaInt<int> defines a different type for each distinct compile-time constant integral parameter. That is, instantiations with different integer values form distinct types, so that bslmf::MetaInt<0> is a distinct type from bslmf::MetaInt<1>, which is also distinct from bslmf::MetaInt<2>, and so on.
Usage:
This section illustrates intended usage of this component
Example 1: Compile-Time Function Dispatching:
The most common use of this structure is to perform static function dispatching based on a compile-time calculation. Often the calculation is nothing more than a simple predicate, allowing us to select one of two functions. The following function, doSomething, uses a fast implementation (e.g., memcpy) if the parameterized type allows for such operations, otherwise it will use a more generic and slower implementation (e.g., copy constructor).
  template <class T>
  void doSomethingImp(T *t, bslmf::MetaInt<0>)
  {
      // slow generic implementation
      (void) t;
      // ...
  }

  template <class T>
  void doSomethingImp(T *t, bslmf::MetaInt<1>)
  {
      // fast implementation (works only for some T's)
      (void) t;
      // ...
  }

  template <class T, bool IsFast>
  void doSomething(T *t)
  {
      doSomethingImp(t, bslmf::MetaInt<IsFast>());
  }
The power of this approach is that the compiler will compile only the implementation selected by the MetaInt argument. For some parameter types, the fast version of doSomethingImp would be ill-formed. This kind of compile-time dispatch prevents the ill-formed version from ever being instantiated.
  int main()
  {
      int i;
      doSomething<int, true>(&i); // fast version selected for int

      double m;
      doSomething<double, false>(&m); // slow version selected for double

      return 0;
  }
Example 2: Reading the VALUE Member:
In addition to forming new types, the value of the integral parameter to MetaInt is "saved" in the enum member VALUE, and is accessible for use in compile-time or run-time operations.
  template <int V>
  unsigned g()
  {
      bslmf::MetaInt<V> i;
      assert(V == i.VALUE);
      assert(V == bslmf::MetaInt<V>::VALUE);
      return bslmf::MetaInt<V>::VALUE;
  }

  int main()
  {
      int v = g<1>();
      assert(1 == v);
      return 0;
  }