如何确定通用容器搜索函数中的数据类型
我主要是一名 C 开发人员,但开始越来越多地使用 C++。
我下面有一个模板化函数,它将在不同类型的 STL 容器中搜索值并进行一些处理。
我知道编译器将根据传递的数据类型生成不同的函数。
在我的情况下如何确定元素类型?我无法使用 auto,因为我的代码应该在没有 C++11 标志的情况下进行编译。
template <typename T, typename T_it>
void ProcessContainer(T con, T_it it )
{
typename N;
for (it = con.begin(); it != con.end(); ++it )
{
//auto element = *it; - Can't use auto in my case
// other processing.. not included
}
}
I am mainly a C developer, but starting to use C++ more and more.
I have a templated function below which will search for values in STL containers of different types and do some processing.
I understand that the compiler will generate different functions depending on which data types are passed.
How do I determine the element type here in my situation? I can't use auto because my code should be compiled without the C++11 flag.
template <typename T, typename T_it>
void ProcessContainer(T con, T_it it )
{
typename N;
for (it = con.begin(); it != con.end(); ++it )
{
//auto element = *it; - Can't use auto in my case
// other processing.. not included
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
标准容器有一个类型成员名称
value_type
,它表示容器中元素的类型,您可以使用它来创建对象,例如还有
std::iterator_traits
这也将为您提供迭代器指向的类型,这将是像这样使用The standard containers have a type member name
value_type
that represents the type of the elements in the container and you can use that to create your object likeThere is also
std::iterator_traits
that will also give you the type that the iterator points to and that would be used like另一种选择是您可以将函数拆分为多个函数,并让编译器推断元素类型:
但是从我的角度来看,@NathanOliver 提供的解决方案更好。
Another option is you can split your function into several functions and let compiler to deduct the element type:
However from my point of view the solution provided by @NathanOliver is better.