title: C++ boost::variant generic converter
body: <p>I've been trying for the last three day to figure out how to implement a generic way of getting the value out of a boost::variant&lt;...>, but it's been quite difficult.</p>
  
  <p>Here is the solution I could come up with, which it not at all generic:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include "boost\variant\variant.hpp"
  
  using MyVariant = boost::variant&lt;int, std::string&gt;;
  
  class VariantConverter : public boost::static_visitor&lt;&gt;
  {
  private:
      mutable int _int;
      mutable std::string _string;
  
      static VariantConverter apply(MyVariant&amp; v) 
      {
          VariantConverter res;
  
          v.apply_visitor(res);
  
          return res; // copy will be elided, right?
      }
  
  public:
      void operator()(int&amp; i) const
      {
          _int = i;
      }
  
      void operator() (std::string&amp; s) const
      {
          _string = s;
      }
  
      static int to_int(MyVariant v) 
      {
          return apply(v).from_int();
      }
  
      static std::string to_string(MyVariant v) 
      {
          return apply(v).from_string();
      }
  
      int from_int() 
      { 
          return _int; 
      };
  
      std::string from_string() 
      { 
          return _string; 
      };
  };
  
  int main()
  {
      using namespace std;
  
      MyVariant v = 23;
  
      int i = VariantConverter::to_int(v);
  
      cout &lt;&lt; i &lt;&lt; endl;
  
      v = "Michael Jordan";
  
      std::string s = VariantConverter::to_string(v);
  
      cout &lt;&lt; s.c_str() &lt;&lt; endl;
  
      cin.get();
  
      return 0;
  }
  </code></pre>
  
  <p>I'd appreciate it if someone could guide me towards a better solution.</p>
  
  <p>Or perhaps someone could explain to me the rationale behind this:</p>
  
  <p>if I declare a:</p>
  
  <pre><code>using MyVariant = boost::variant&lt;int, std::string&gt;;
  </code></pre>
  
  <p>and then a:</p>
  
  <pre><code>ConverterToInt : basic_visitor&lt;int&gt; {
  public:
      int operator() (int i) { return i; };
  };
  </code></pre>
  
  <p>Why is it that when I try to apply the ConverterToInt to a MyVariant as such:</p>
  
  <pre><code>ConverterToInt cti;
  
  MyVariant i = 10;
  
  i.apply_visitor(cti);
  </code></pre>
  
  <p>I get a compiler error about trying to find a operator() that takes a std::string?</p>
  
  <p>It seems to me that apply_visitor is trying to call an operator() for each of the types MyVariant can take. Is that so? If it is, why? How can i avoid this behavior?</p>
  
  <p>Cheers!</p>