【问题标题】:Template arguement for comparator when passing priority queue to a function将优先级队列传递给函数时比较器的模板参数
【发布时间】:2022-02-01 08:26:30
【问题描述】:

我是 C++ 新手,仍在学习这些概念。我正在尝试将带有自定义比较器的优先级队列传递给模板化函数。当我将它传递给函数定义中的函数时,我想在优先级队列模板参数列表中抽象比较器类型。下面是我正在尝试做的一个示例。

File1.h

struct my_comparator
{
bool operator()(const some_type* c1, const some_type* c2){
c1->property < c2->property;
}
another_funtion(….)
{
std::priority_queue<const some_type*, std::vector<const some_type*>, my_comparator> my_queue;

some_function(my_queue);
}
File2.h

some_function(std::priority_queue<const some_type*, std::vector<const some_type*>, comparator_type> queue_)
{
//implementation
}

我想了解在 some_function 定义的优先级队列模板中作为比较器类型传递的内容,以便它可以接受我在调用函数的文件中定义的任何自定义比较器(遵守所需的格式)(在这种情况下是 File1.h)。

P.S:这是我第一次在这里发帖。对于任何格式错误,请提前致歉。谢谢!

【问题讨论】:

    标签: c++ templates comparator priority-queue abstraction


    【解决方案1】:

    您似乎希望允许使用任何比较器(在您的自定义类型 some_type 上)。为此,您可以简单地使用(我假设您确实想要按值传递):

    template<class TComparator>
    void some_function(std::priority_queue<const some_type*, std::vector<const some_type*>, TComparator> queue) 
    { 
      // ... 
    }
    

    然后,让编译器推断您的论点。假设你有两个比较器 my_comp1my_comp2,那么你可以有:

    template<class TComparator>
    using my_queue_t = std::priority_queue<const some_type*, std::vector<const some_type*>, TComparator>;
    
    my_queue_t<my_comp1> q1;
    my_queue_t<my_comp2> q2;
    
    // Do something with them
    some_function(q1);
    some_function(q2);
    

    比较器类型将由编译器自动推断。您还可以将模板别名分隔到另一个文件(例如,在您的类型 some_type 附近)并在两个文件中使用。

    【讨论】:

      【解决方案2】:

      你可以一路让some_function泛型接受任何类型:

      template <typename P>
      void some_function(P queue_)
      {
          //implementation
      }
      

      (另请参见此处的示例:https://en.cppreference.com/w/cpp/container/priority_queue)或使用别名

      using priority_queue_type = std::priority_queue<const some_type*, std::vector<const some_type*>;
      

      并使其在两个标题中都可用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多