Semantics of formatting semantics
I was wondering what is the semantics of copying boost variants. I checked the source code and it puzzled me a little, so I was wondering, in the example code, if my function getVal(name)
makes a copy of the base vector when it returns? If so, should I change it to be a reference (&) instead?
using Val = boost::variant<std::vector<int>, std::vector<std::string>>;
Val getVal(std::string& name) {
return map[name];// where map is std::map<std::string, Val>
}
source to share
Yes, yours getVal
returns a copy of all vectors (including copies of all strings of elements, for example).
Yes, a link will result instead.
Note , you can also have a variant where the link is stored. In this case, returning it with "value" still has the same semantics as returning a reference:
using Ref = variant<std::vector<int>&, std::vector<std::string>&>;
Ref getVal(std::string& name) {
return map[name]; // where map is std::map<std::string, Val>
}
Complete sample with necessary mechanics to convert from Ref
to Val
(and vice versa):
#include <boost/variant.hpp>
#include <map>
#include <vector>
#include <string>
using Val = boost::variant<std::vector<int>, std::vector<std::string>>;
using Ref = boost::variant<std::vector<int>&, std::vector<std::string>& >;
std::map<std::string, Val> map {
{ "first", std::vector<int> { 1,2,3,4 } },
{ "2nd", std::vector<std::string> { "five", "six", "seven", "eight" } }
};
namespace { // detail
template <typename T>
struct implicit_convert : boost::static_visitor<T> {
template <typename U> T operator()(U&& u) const { return std::forward<U>(u); }
};
}
Ref getVal(std::string& name) {
return boost::apply_visitor(implicit_convert<Ref>(), map[name]);
}
#include <iostream>
int main() {
for (auto i : boost::get<std::vector<int> >(map["first"])) std::cout << i << " ";
for (auto i : boost::get<std::vector<std::string> >(map["2nd"])) std::cout << i << " ";
}
Output:
1 2 3 4 five six seven eight
Without copying all vectors
source to share