25

code:

template <typename element_type, typename container_type = std::deque<element_type> >
class stack
{
    public:
        stack() {}
        template <typename CT>
        stack(CT temp) : container(temp.begin(), temp.end()) {}
        bool empty();
   private:
       container_type container;
};

template <typename element_type, typename container_type = std::deque<element_type> >
bool stack<element_type, container_type>::empty()
{
    return container.empty();
}

When I compile it gives the error.

default argument for template parameter for class enclosing 'bool stack<element_type,container_type>::empty()'

Why is the compiler complaining and how can I make it work?

2
  • Is this really the complete error message? It looks like there is something missing... Jun 12, 2013 at 16:59
  • 1
    @TimoGeusch: It is indeed when compiled with g++ and --std=c++0x. While actually correct, it is not very helpful at first glance :/ Jun 12, 2013 at 17:15

2 Answers 2

35

You attempt to provide a default argument for the second template parameter to stack twice. Default template arguments, just like default function arguments, may only be defined once (per translation unit); not even repeating the exact same definition is allowed.

Just type the default argument at the beginning where you define the class template. After that, leave it out:

template<typename element_type,typename container_type>
bool stack<element_type,container_type>::empty(){
    return container.empty();
}
0
3

That default parameter is, by syntax, a default parameter to the class, and it only makes sense at the class declaration.

If you would call that function ...

stack<foo,bar>().empty();

you only have the template parameters on the site of the class name, for which you already provided default parameters at the point of the template class declaration.

You can solve the issue by simply removing the default parameter from the function definition:

template<typename element_type,typename container_type>
bool stack<element_type,container_type>::empty(){
    return container.empty();
}
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.