I'm using boost::variant
already for a while, but there are still some questions that leave me puzzled.
The following code is not compiling, as I'm trying to store a std::pair<int, int>
to a boost::variant
, that can only contain int
, double
and std::string
. Still I need the function convert
, but it should throw an exception in case I'm trying to store a type in the boost::variant
that it will not fit.
#include <iostream>
#include <boost/variant.hpp>
#include <vector>
typedef boost::variant<int, double, std::string> TVar;
template<typename T>
std::vector<TVar> convert(const std::vector<T>& vec) {
std::vector<TVar> ret;
for (size_t t = 0; t < vec.size(); t++) {
ret.push_back(vec[t]);
}
return ret;
}
int main(int arg, char** args) {
{
std::vector<double> v = { 3,6,4,3 };
auto ret=convert(v);
std::cout << ret.size() << std::endl;
}
{
std::vector<bool> v = { true, false, true };
auto ret=convert(v);
std::cout << ret.size() << std::endl;
}
{
std::vector<std::pair<int, int>> v = { std::make_pair<int, int>(5,4) };
auto ret = convert(v);
std::cout << ret.size() << std::endl;
}
return 0;
}
It seems, that std::enable_if
might be part of the solution, but I was unable to bring this to an end.