模板由操作员填写
你能在C++中使用模板(或类似的)来指定函数中执行哪个操作吗?
我不知道如何更清楚地解释它,所以我将向您展示如何在代码中完成(但没有):
template <operator OPERATION> int getMaxOrMin(int a, int b) {
return a OPERATION b ? a : b;
}
在哪里找到 a 或 b 的最大值或最小值(这是我的位置)伪语法有点令人困惑,请耐心等待):
int max = getMaxOrMin< > > (a, b);
int min = getMaxOrMin< < > (a, b);
我知道这根本不是怎么做的(因为它甚至在语法上没有意义),但我希望这能澄清我想做的事情的类型。
我想知道这一点的原因是我正在制作一个 PriorityQueue 实现,如果能够在支持最大堆或最小堆之间轻松切换,而无需复制和粘贴代码来创建两个不同的类,那就太好了。
我知道我可以用宏来做到这一点,但我知道如何做到这一点的唯一方法是给我一个最大堆或一个最小堆,但不能在同一个编译中同时提供两者。不过,我可能忽略了一种方式。
Can you use templates (or the like) in C++ to specify which operation is done in a function?
I don't know how to explain it more clearly, so I'll show you how it could be (but isn't) done in code:
template <operator OPERATION> int getMaxOrMin(int a, int b) {
return a OPERATION b ? a : b;
}
where finding the maximum or the minimum of a or b would be (this is where my pseudo-syntax gets a little confusing, bear with me):
int max = getMaxOrMin< > > (a, b);
int min = getMaxOrMin< < > (a, b);
I know that's not how to do it at all (because it doesn't even syntactically make sense), but I hope that clarifies the type of thing I want to do.
The reason behind me wondering this is I'm making a PriorityQueue implementation, and it would be nice to easily switch between the backing being a max-heap or a min-heap on the fly without copying and pasting code to make two different classes.
I know I could do it with a macro, but the only way I'd know how to do that would give me either a max-heap or a min-heap, but not both in the same compilation. I'm probably overlooking a way, though.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
做
std::map
和朋友所做的事情:将比较函数/函子作为模板参数。请参阅std::less
和std::greater
。请记住,标准库已经拥有一个开发良好且经过调试的优先级队列,您可以将其与任意比较函数一起使用。
Do what
std::map
and friends do: Take a comparison function/functor as your template parameter. Seestd::less
andstd::greater
.Do remember that the standard library already has a well developed and debugged priority queue that you can use with an arbitrary comparison function.
是的,但是您需要像函子一样定义它:
现在您可以像这样使用它:
这看起来需要很多工作。但标准中有很多预定义的函子。在此页面上,向下滚动到“6:函数对象”。
对于你的情况有:
所以代码变成:
Yes but you need to define it like a functor:
Now you can use it like this:
That seems like a lot of work. But there are a lot of predefined functors in the standard. On this page scroll down to "6: Function Objects".
For your situation there is:
So the code becomes: