title: visitor pattern for boost::any
body: <p>I found this <a href="https://gist.github.com/2945472">https://gist.github.com/2945472</a> but I need an implementation that does not depend on c++11. I tried my hand at converting it to use only boost, but I'm having some trouble.</p>
  
  <p>Here is what I came up with:</p>
  
  <pre><code>#include &lt;boost/any.hpp&gt;
  #include &lt;boost/function.hpp&gt;
  #include &lt;boost/bind.hpp&gt;
  #include &lt;boost/lambda/lambda.hpp&gt;
  #include &lt;boost/unordered_map.hpp&gt;
  
  struct type_info_hash {
      std::size_t operator()(std::type_info const &amp; t) const {
          return t.hash_code();
      }
  };
  
  struct equal_ref {
      template &lt;typename T&gt; bool operator()(boost::reference_wrapper&lt;T&gt; a,boost::reference_wrapper&lt;T&gt; b) const {
          return a.get() == b.get();
      }
  };
  struct any_visitor {
      boost::unordered_map&lt;boost::reference_wrapper&lt;std::type_info const&gt;, boost::function&lt;void(boost::any&amp;)&gt;, type_info_hash, equal_ref&gt; fs;
  
      template &lt;typename T&gt; void insert_visitor(boost::function&lt;void(T)&gt; f) {
          try {
              fs.insert(std::make_pair(boost::ref(typeid(T)), boost::bind(f, boost::any_cast&lt;T&gt;(boost::lambda::_1))));
          } catch (boost::bad_any_cast&amp; e) {
              std::cout &lt;&lt; e.what() &lt;&lt; std::endl;
          }
      }
  
      bool operator()(boost::any &amp; x) {
          boost::unordered_map&lt;boost::reference_wrapper&lt;std::type_info const&gt;, boost::function&lt;void(boost::any&amp;)&gt;, type_info_hash, equal_ref&gt;::iterator it = fs.find(boost::ref(x.type()));
          if (it != fs.end()) {
              it-&gt;second(x);
              return true;
          } else {
              return false;
          }
      }
  };
  
  struct abc {};
  
  void fa(int i) { std::cout &lt;&lt; "fa(" &lt;&lt; i &lt;&lt; ")" &lt;&lt; std::endl; }
  void fb(abc) { std::cout &lt;&lt; "fb(abc())" &lt;&lt; std::endl; }
  
  int main() {
      any_visitor f;
      f.insert_visitor&lt;int&gt;(fa);
      f.insert_visitor&lt;abc&gt;(fb);
  
      std::vector&lt;boost::any&gt; xs;
      xs.push_back(1);
      xs.push_back(abc());
      xs.push_back(1.5);
  
      for (auto &amp; x : xs) {
          if (!f(x)) std::cout &lt;&lt; "no visitor registered" &lt;&lt; std::endl;
      }
  }
  </code></pre>
  
  <p>I'm getting a bad_any_cast when inserting into the map. Shouldn't any_cast only be called by it->second(x) ? What am I doing wrong?</p>