Boost logo

Boost Users :

From: Patrick Guio (patrick.guio_at_[hidden])
Date: 2001-12-01 07:09:21


Dear all,
I am trying to use the any class in a project. I would need to print
elements of a vector<any>. I have come to the following solution as an
example:

template<class T>
inline ostream& operator<<(ostream &os, const vector<T> &v)
{
  vector<T>::const_iterator iter(v.begin());
  for (int c(0), n(v.size()); c<n-1; c++) os << *iter++ << ',';
  return os << *iter;
}
typedef vector<bool> vectb;
int main()
{
  vector<any> values;
  double f(2.0);
  string s("hello");
  int i(100);
  bool b(false);
  vectb vectbool;

  vectbool.push_back(true);
  vectbool.push_back(false);
  vectbool.push_back(true);
  vectbool.push_back(true);
  vectbool.push_back(false);
  vectbool.push_back(true);

  values.push_back(f);
  values.push_back(s);
  values.push_back(i);
  values.push_back(b);
  values.push_back(vectbool);
  for (vector<any>::iterator i(values.begin()), last(values.end());
      i!=last; i++) {
    if (any_cast<bool>(i)) cout << *any_cast<bool>(i) << endl;
    else if (any_cast<int>(i)) cout << *any_cast<int>(i) << endl;
    else if (any_cast<float>(i)) cout << *any_cast<float>(i) << endl;
    else if (any_cast<double>(i)) cout << *any_cast<double>(i) << endl;
    else if (any_cast<string>(i)) cout << *any_cast<string>(i) << endl;
    else if (any_cast<vectb>(i)) cout << *any_cast<vectb>(i) << endl;
  }
}

But I would like a more general solution without to make assumptions about
the type. Do you have any ideas?
Another point is that I cannot figure out how to convert the solution
below in terms of a friend ostream& operator<<(ostream &os, const any
&rhs)
I cannot get this compiled with g++ v 2.95
 friend ostream& operator<<(ostream &os, const any &rhs)
{
return os << *any_cast<bool>(rhs);
}

Sincerely, Patrick

======================================================================
                                  Patrick Guio
                    Institute of Physics, University of Oslo
                      P.O. box 1048, Blindern, N-0316 Oslo
               Tel : (+47) 22 84 40 60 - Fax : (+47) 22 85 56 71
                        E-mail : patrick.guio_at_[hidden]
                  URL : http://folk.uio.no/~patricg


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net