I am using BOOST_STRONG_TYPEDEF
to prevent misuses of different string-based ID types. I am however running into compatibility problems between the original type and its typedef.
I have an std::string
which contains a list of IDs, separated by commas. I need to store them into a set. The code would look like:
#include <boost/algorithm/string/split.hpp>
#include <boost/serialization/strong_typedef.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <set>
#include <vector>
BOOST_STRONG_TYPEDEF(std::string, MY_ID)
int main()
{
std::string line("ID1,ID2,ID3");
// Use boost::split to get all the strings into a vector
std::vector<std::string> id_vec;
boost::split(id_vec, line, boost::is_any_of(","));
// Generate a set of MY_ID. Do not use range constructor since the compiler
// error is clearer this way
std::set<MY_ID> ids;
for (auto const & id : id_vec)
{
ids.insert(id);
}
}
This doesn't compile, since std::string
cannot be inserted into a std::set<MY_ID>
. However, if I declared the vector to be of type std::vector<MY_ID>
it would not work with boost::split
.
I have found a work around by adding a temporal variable when inserting:
for (auto const & id : id_vec)
{
MY_ID tmp(id);
ids.insert(tmp);
}
This works but seems hacky. Is there a more concise way?
Aucun commentaire:
Enregistrer un commentaire