如何测试模板参数是否是一对关联容器?
假设我想要创建一个模板函数,它返回任何 stl 容器的第一个元素。一般的方法是:
template<typename Container>
Container::value_type first(Container c){
return *(c.begin());
}
这适用于向量、列表、双端队列、集合等。
但是,对于成对关联容器(std::map),
return c.begin()->second;
如果我有成对关联容器,我该如何测试(在函数中或使用模板专业化)?
STL容器似乎没有附加任何特征。是否可以检查它是否有 ::key_type ?
Let's imagine I want to make a templated function that returns the first element of any stl container. The general way would be :
template<typename Container>
Container::value_type first(Container c){
return *(c.begin());
}
This works for vectors, lists, deques, sets and so on.
However, for pair associative containers (std::map), if would like to have
return c.begin()->second;
How could I test (in the function or with template specialization) if I have an pair associative container ?
STL container seem to have no traits attached to it. Is it possible to check if it has a ::key_type ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以很容易地做到这一点:
但我应该注意,我可能会添加一个测试来查看容器是否为空...因为如果容器为空,您正在执行未定义的行为。
运动中:
示例无耻地取自
litb
;)You can do quite easily:
I should note though, that I would probably add a test to see if the container is
empty
... Because if the container isempty
, you're on for undefined behavior.In movement:
Example shamelessly taken from
litb
;)这个有效:(
输出
4243
)This one works:
(outputs
4243
)使用模板函数的特化:
Use specialization of template function: