template to return specific type
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 version attribute<T>(const std::string& attribute)
.
The normal version would do:
return boost::get<T>(find_attribute<variant>(attribute));
But remeber that template are evaluated at compile time!
If find_attribute
is 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.
How should I implement this so I can either just return the variant or the type contain in the variant.
You can't. Template parameters are fixed at compile-time, so when your program finds out what it would have to return it is all long since set into stone.
精彩评论