返回特定类型的模板
我有一个模板函数,我希望返回 T 的类型或变体。我尝试执行以下操作,但是编译器抱怨它无法将“variant”转换为 int(我在 T=int 中使用此函数)。
我应该如何实现这个,以便我可以只返回变体或变体中包含的类型。
它是从向量结构中得到的。
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.
}
}
}
}
}
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.
}
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以为
find_attribute(const std::string& attribute)
创建一个模板特化,它返回一个变体和一个普通版本attribute(const std::字符串和属性)
。普通版本可以:
但请记住模板是在编译时评估的!
如果
find_attribute
是成员函数,则您仅可以将其与 msvc 编译器一起使用。如果您无法进行模板专门化,则可以将函数命名为不同的名称。
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_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.
你不能。模板参数在编译时是固定的,所以当你的程序发现它必须返回什么时,它就已经是一成不变的了。
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.