1

I have a function where 'T' can either be a queue or a stack. Currently for the function signature I have:

template <class T>
void foo(T<string> baa){

  //do something
}

Within foo I want to call T.pop() but I cannot do so.

I then wrote two version of pop, one for a queue and one for a stack.

string bar(stack<string> & baa){
  string t=baa.top();
  baa.pop();
  return t;
}
string bar(queue<string> & baa){
  string t=baa.front();
  baa.pop();
  return t;
}

I then tried to do this but it wouldn't work. How am I supposed to do this?

template <class T>
void foo(T<string> baa){
  //do something
  string baz=bar(baa);
}

EDIT:I forgot that top() simply removes the top element. I have now edited the code fragment to reflect those changes. However it still isn't working.

3
  • Those are not classes, but template classes. Commented Jan 27, 2013 at 20:20
  • 1
    Why enforcing T<string>? Wouldn't T be sufficient? Commented Jan 27, 2013 at 20:21
  • 2
    Have you checked the manual for what pop() does? Commented Jan 27, 2013 at 20:22

1 Answer 1

2

If you really want to do something like this, then syntactically what you need is template template parameters:

template<template<typename> class T>
void foo(T<string>& baa)
{
    ...
}

However, be aware that the template parameters of the template template parameter T must match exactly the ones of the template template argument, even though those parameters have default argument values.

In other words, since STL's stack and queue container adapters accept two type parameters (even though the second one has a default argument value), if you want them to be deduced as the template template arguments of your function template foo(), the template template parameter T must take two type parameters:

template<template<typename, typename> class T, typename C>
void foo(T<string, C>& baa)
{
    ...
}

I shall point out, though, that your current needs do not seem to require such a design. This is enough:

template<typename T>
string bar(T& baa)
{
    string t = baa.front();
    baa.pop();
    return t;
}

You would be forced to adopt the solution with template template parameters only if you had other function template overloads of bar() that need to work on non-container types, but again this does not seem to be your case.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it seemed to have worked after I didn't force 'foo' to be of type T<string>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.