Reputation: 111
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.
Upvotes: 1
Views: 69
Reputation: 126562
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.
Upvotes: 2