我希望并认为这个问题不是 C++ template typedef 的重复问题所以这里是:
我想知道社区是否可以帮我看看有没有办法缩短template<typename ORDER> std::priority_queue<int, std::vector<int>, ORDER>
用typedef
没有特化。我要打折#define
请回答这个问题。我不确定 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
.
免责声明:编译器未触及代码。
在其他新闻中:
- 全部大写很碍眼,将它用于除宏名称之外的任何其他内容都与宏命名的通用约定相冲突。
关于c++ - std::priority_queue 声明可以在没有专门化的情况下缩短吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39802793/