Y
Your Name
Hi,
I use templated functions to handle "ToString" functionality. For
example:
template<> void ToString<int>(std::string &s, int &value)
{
s = str(boost::format("%1$d") % value);
}
template<> void ToString<float>(std::string &s, float &value)
{
s = str(boost::format("%1$1.7g") % value);
}
// ... lots more specialization ...
Now I'd like to add a version of ToString for std::vector. But all I
really want to do is call the corresponding ToString<element_type> where
"element_type" is the type of element in the vector. Is it possible to
handle this with a single ToString function, or do I have to write one
for every possible type of vector element? It seems like a waste, since
the code in every function would be identical except for what's inside
the <> brackets.
Here's kind of a psuedo-code for what I want, but I don't know how to
make the syntax work...
// Create a string of the form "[1, 2, 3, 4, 5]"
template<>
void ToString<std::vector<element_type>>(std::string &s,
std::vector<element_type> &value)
{
s = "[";
std::vector<element_type>::iterator i = value.begin();
while (i != value.end())
{
std::string temp;
ToString<element_type>(temp, *i);
i++;
s += temp;
if (i != value.end())
{
s += ", ";
}
}
s += "]";
}
Hope the example makes sense. Thanks.
Pat
I use templated functions to handle "ToString" functionality. For
example:
template<> void ToString<int>(std::string &s, int &value)
{
s = str(boost::format("%1$d") % value);
}
template<> void ToString<float>(std::string &s, float &value)
{
s = str(boost::format("%1$1.7g") % value);
}
// ... lots more specialization ...
Now I'd like to add a version of ToString for std::vector. But all I
really want to do is call the corresponding ToString<element_type> where
"element_type" is the type of element in the vector. Is it possible to
handle this with a single ToString function, or do I have to write one
for every possible type of vector element? It seems like a waste, since
the code in every function would be identical except for what's inside
the <> brackets.
Here's kind of a psuedo-code for what I want, but I don't know how to
make the syntax work...
// Create a string of the form "[1, 2, 3, 4, 5]"
template<>
void ToString<std::vector<element_type>>(std::string &s,
std::vector<element_type> &value)
{
s = "[";
std::vector<element_type>::iterator i = value.begin();
while (i != value.end())
{
std::string temp;
ToString<element_type>(temp, *i);
i++;
s += temp;
if (i != value.end())
{
s += ", ";
}
}
s += "]";
}
Hope the example makes sense. Thanks.
Pat