Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can't cast <code>_1</code> to <code>T</code> (at the time of the bind expression). </p> <p>You need a lazy cast. Perhaps define a function and use a nested bind expression, or use Boost Phoenix with a custom <code>any_cast</code> actor.</p> <p>Here's the nested bind approach:</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 42; // 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; static T any_cast_f(boost::any&amp; any) { return boost::any_cast&lt;T&gt;(any); } 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::bind(any_cast_f&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 it=xs.begin(); it!=xs.end(); ++it) if (!f(*it)) std::cout &lt;&lt; "no visitor registered" &lt;&lt; std::endl; } </code></pre> <p>Prints output:</p> <pre><code>fa(1) fb(abc()) no visitor registered </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload