I have a template function that I wish to return either the type of T or a variant. I tried to do as follows, however the compiler complains it cannot convert ‘variant’ to int (where I use this function with T=int).
How should I implement this so I can either just return the variant or the type contain in the variant.
It is gotten out of a vector structs.
template <typename T>
T find_attribute(const std::string& attribute, bool isVariant = false)
{
std::vector<boost::shared_ptr<node> >::iterator nodes_iter = _request->begin();
for (; nodes_iter != _request->end(); nodes_iter++)
{
size_t sz = (*nodes_iter)->attributes.size();
std::vector<node::attrib>::iterator att_iter = (*nodes_iter)->attributes.begin();
for (; att_iter != (*nodes_iter)->attributes.end(); att_iter++)
{
if (att_iter->key.compare(attribute) == 0)
{
if (isVariant)
{
return att_iter->value; //return variant
}
else
{
return boost::get<T>(att_iter->value); // return type inside variant as given by T.
}
}
}
}
}
You can create a template specialisation for
find_attribute<boost::variant>(const std::string& attribute)that return a variant and a normal versionattribute<T>(const std::string& attribute).The normal version would do:
But remeber that template are evaluated at compile time!
If
find_attributeis a member function, you can use this only with the msvc compiler.If you can’t do template specialisation, you could name the functions different.