cout vector of std::any

Viewed 4013

I have a std::vector of std::any, all of which can be printed via << (e.g., only ints and floats). I'd love to have something like

#include <experimental/any>
#include <iostream>
#include <vector>

int main() {
  std::vector<std::experimental::any> v;

  v.push_back(1);
  v.push_back(3.14);

  for (const auto& a: v) {
    std::cout << a << std::endl;
  }

  return 0;
}

but that doesn't work since std::any doesn't know <<:

error: no match for ‘operator<<’

The only workaround I've come up with so far is to explicitly cast the vector items into whatever data type might be in it, e.g.,

#include <experimental/any>
#include <iostream>
#include <vector>

int main() {
  std::vector<std::experimental::any> v;

  v.push_back(1);
  v.push_back(3.14);

  for (const auto& a: v) {
    try {
        std::cout << std::experimental::any_cast<int>(a) << std::endl;
    } catch (const std::experimental::fundamentals_v1::bad_any_cast&)
    {}

    try {
        std::cout << std::experimental::any_cast<double>(a) << std::endl;
    } catch (const std::experimental::fundamentals_v1::bad_any_cast&)
    {}
  }

  return 0;
}

This is (perhaps unnecessarily) verbose and also rather inflexible since once has to know all data types that might occur in the vector.

Is there a variant of vector<any> printing without those disadvantages?

1 Answers
Related