1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| #include <boost/variant.hpp>
#include <type_traits>
#include <vector>
struct Colonne
{
template<class T>
void ajouteElement(T x) {
boost::apply_visitor([&x, this](auto & vec) {
this->ajouteElement_impl(vec, x);
}, variant);
}
template<class Visitor>
void apply(Visitor v) const {
boost::apply_visitor(v, variant);
}
private:
template<class T>
void ajouteElement_impl(std::vector<T> & vec, T x) {
vec.push_back(x);
}
template<class T, class U>
std::enable_if_t<std::is_arithmetic<T>{} && std::is_arithmetic<U>{}>
ajouteElement_impl(std::vector<T> & vec, U x) {
std::vector<U> new_vec(begin(vec), end(vec));
new_vec.push_back(x);
variant = std::move(new_vec);
}
boost::variant<std::vector<bool>, std::vector<float>, std::vector<int>> variant;
};
#include <iostream>
char const * get_type(std::vector<float> const &) { return "vector<float>"; }
char const * get_type(std::vector<bool> const &) { return "vector<bool>"; }
char const * get_type(std::vector<int> const &) { return "vector<int>"; }
std::ostream & operator << (std::ostream & out, Colonne const & colonne) {
colonne.apply([&out](auto & vec) {
out << get_type(vec) << ": ";
for (auto && x : vec) {
out << x << ", ";
}
});
return out;
}
int main() {
Colonne colonne;
colonne.ajouteElement(1); // int
std::cout << colonne << "\n";
colonne.ajouteElement(1.4f); // float
std::cout << colonne << "\n";
colonne.ajouteElement(0); // int
std::cout << colonne << "\n";
colonne.ajouteElement(true); // bool
std::cout << colonne << "\n";
colonne.ajouteElement(false); // bool
std::cout << colonne << "\n";
} |
Partager