std::priority_queue 声明可以在没有专业化的情况下缩短吗?

Can std::priority_queue declaration be shortened without specialization?

我希望并认为这个问题不是 C++ template typedef 的重复,所以这里是:

我想知道社区是否可以帮助我看看是否有一种方法可以缩短 template<typename ORDER> std::priority_queue<int, std::vector<int>, ORDER> typedef 而无需 专业化。请为这个答案打折 #defines。我不确定 C++11 的 alias 功能是否适用于此,但我还需要将其作为答案打折,因为我使用的编译器是 C++03.

这里是一些示例代码的上下文:

#include <iostream>
#include <queue>

namespace
{

template<typename ORDER>
std::priority_queue<int, std::vector<int>, ORDER> GetPriorityQ(std::vector<int> numbers)
{
    std::priority_queue<int, std::vector<int>, ORDER> theQueue;

    for (int i = 0; i < numbers.size(); ++i)
    {
        theQueue.push(numbers[i]);
    }

    return theQueue;
};

class Less
{
public:
    operator()(int a, int b)
    {
        return (a < b);
    }
};

class More
{
public:
    operator()(int a, int b)
    {
        return (b < a);
    }
};

}

int main(int argc, char* argv[])
{
    std::vector<int> v({4, 9, 2, 8});

    std::priority_queue<int, std::vector<int>, Less> pqLess = 
        GetPriorityQ<Less>(v);

    std::cout << "Ordered by Less:" << std::endl;
    while (!pqLess.empty())
    {
        std::cout << pqLess.top() << std::endl;
        pqLess.pop();
    }

    std::priority_queue<int, std::vector<int>, More> pqMore = 
        GetPriorityQ<More>(v);

    std::cout << "Ordered by More:" << std::endl;
    while (!pqMore.empty())
    {
        std::cout << pqMore.top() << std::endl;
        pqMore.pop();
    }

    return 0;
}

我知道我可以缩短优先级队列的 专业化 ,例如...

typedef std::priority_queue<int, std::vector<int>, Less> LessQueue;

...但我想知道是否有一种方法可以缩短它 而无需 专业化,这样我就可以保持 GetPriorityQ(...) 通用(即如果我专业化priority_queue 的 typedef,我必须实现尽可能多的 GetPriorityQ(...) 特化,我想避免)。

也就是说,在伪代码中,有没有办法做类似的事情:

typedef std::priority_queue<int, std::vector<int>, ORDER> OrderedQ

...

template<typename ORDER>
OrderedQueue<ORDER> GetPriority(std::vector<int> numbers)
{
   ...
}

...

int main(int argc, char* argv[])
{
    ...
    OrderedQueue<Less> pqLess = GetPriorityQ<Less>(v);
    ...
}

我问的原因是定义 priority_queue 的行的长度变得很长,即使在这个简化的示例中也是如此。我正在处理的实际代码(这个示例是对其的简化)要长得多,因此难以阅读。

答案本身不一定是 typedef。任何与 C++03 兼容且不使用 #define 的东西都可以。

谢谢。

对于 C++03,您无法避免一些措辞,即(在模板代码中)typename,但除此之外:

template< class Order >
struct Pq
{
    typedef std::priority_queue<int, std::vector<int>, Order> T;
};

所以现在你可以写例如Pq<OrderA>::T,更短。或者,当 OrderA 是模板参数时,typename Pq<OrderA>::T.

免责声明:编译器未触及代码。


在其他新闻中:

  • 全部大写是一种眼中钉,将它用于除宏名称之外的任何其他内容都与宏命名的通用约定冲突。