문제

I would like to have a Queue template class which can specify the internal container structure via the template argument and specialize the Top function (as different container use different function name for accessing the front item), like the following code:

template<class I, class C = std::queue<I>>
class Queue
{
    C items;
public:
    I* Top()
    {
        std::cout << "this is a queue" << std::endl;
        return &items.front();
    }
};

template<class I>
void I* Queue<I, std::priority_queue<I>>::Top()
{
    std::cout << "this is a priority_queue" << std::endl;
    return &items.top();
}

However, this piece of codes cause a lot compilation errors. Does anyone could give me a hint that am I going into a wrong direction of designing the template class? Thanks.

도움이 되었습니까?

해결책

You're trying to partially specialise a (member) function template. Function templates cannot be partially specialised in C++. You'd have to partially specialise the entire class, or find other ways of doing what you want. For example, you could use a trait in Top():

I* Top()
{
    return MyQueueTraits<I, C>::GetTop(items);
}

template <class I, class C>
struct MyQueueTraits
{
  static I* GetTop(C &c) { return &c.front(); }
};

template <class I>
struct MyQueueTraits<I, std::priority_queue<I>>
{
  static I* GetTop(std::pirority_queue<I> &c) { return &c.top(); }
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top