为“ type”做一个共同的功能和“类型”的向量使用C++
我正在编写功能,并遇到了这种情况:
void doSomeThing(std::vector<someType> vec)
{
for(element : vec)
{
// do Something different if it is in vector
}
}
void doSomeThing(someType element)
{
// do Something else if it was not a vector
}
我需要像上面所述的那样分开。我想知道是否有一种方法使用模板来推断这种类型并进行相应的处理?
I was writing functions and came across this situation:
void doSomeThing(std::vector<someType> vec)
{
for(element : vec)
{
// do Something different if it is in vector
}
}
void doSomeThing(someType element)
{
// do Something else if it was not a vector
}
I need them to be separate like above stated. I was wondering if there was a way using templates to deduce the type and do the processing accordingly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,是的,这是可能的。
例如,您可以做;
就个人而言,我会做一些不同的事情 - 而不是为矢量超载,而是对一对迭代器过载。例如,假设
dosomething()
是打印到std :: cout
的功能,它将与任何标准容器中的迭代器一起使用(例如
std ::的特殊性, vector
,std :: list
)或其他任何可以提供有效迭代器的东西。Well, yes, it is possible.
For example, you could do;
Personally, I'd do it slightly differently though - instead of overloading for a vector, I'd overload for a pair of iterators. For example, assuming
doSomething()
is just function that prints tostd::cout
which will work with iterators from any standard container (e.g. specialisations of
std::vector
,std::list
) or anything else that can provide a pair of valid iterators.只需更改,您就可以这样做
With just little changes you can do so
例如,您可以
在此处写一个演示程序。
程序输出是
For example you can write
Here is a demonstration program.
The program output is