title: C++ How to select class via optional typedef, using SFINAE or whatever
body: <p>The user customizes a library template class by defining a class specifying the desired options. Call it a manifest. The idea is to have optional typedefs in the manifest. If the user's manifest contains a typedef for H, for example, I want the library code to use the indicated type as its "H". If there is no typedef in the user's manifest, the library will use a default. </p>
  
  <p>I suspect there is an elegant way to do this by utilizing the new C++11 features, but I am coming up empty. I have a solution, based on the Wikipedia entry for SFINAE. It is ugly. It requires a new template function <strong>has_typedef_H</strong> for each new H. I am vaguely uneasy that it exploits the property that <strong>0</strong> can mean either the integer or a null pointer. Just seems too klugey.</p>
  
  <p>Is there a better way? Preferably one that will work in VC++ 2010?</p>
  
  <p>In the toy example there are five classes, H1, H2, and U0, U1, and U2.  H1 and H2 are examples of "helpers" for a library class L. H1 is the default. The U's are examples of user-defined classes. In the example, I omitted defining a library class L, just using the body of main() to select the H's based upon typedefs in the U's (or the lack thereof). subject of type H2.</p>
  
  <pre>
  <code>
  struct H1{
      void operator() (){ std::cout &LT;&LT; "H1" &LT;&LT std::endl;}
  };
  
  struct H2{
      void operator() (){ std::cout &LT;&LT "H2" &LT;&LT std::endl;}
  };
  
  
  struct default_H: public H1 {};
  
  struct U2 {
      typedef H2 H;
  };
  
  struct U1 {
      typedef H1 H;
  };
  
  struct U0 {
  };
  
  
  template &LT;typename T&GT;
  class has_typedef_H {
  
      typedef char no[false+1];
      typedef char yes[true+1];
  
      template 
      static yes& test(typename C::H*);
  
      template 
      static no& test(...);
  
  public:
      static const bool value = sizeof(test(0))-1; 
  };
  
  
  template&LT;typename U, bool >
  struct type_H_B: public default_H{};
  
  template&LT;typename U>
  struct type_H_B&LT;U, true>: public U::H {};
  
  template&LT;typename U>
  struct H_type: public type_H_B&LT;U, has_typedef_H&LT;U>::value> {};
  
  int main() {
  
      H_type&LT;U0> h0;
      H_type&LT;U1> h1;
      H_type&LT;U2> h2;
  
      // Prints H1 H1 H2
      h0();
      h1();
      h2();
      return 0; 
  }
  </code>
  </pre>