类封闭的模板参数的默认参数

hua*_*als 19 c++ templates

码:

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();
}
Run Code Online (Sandbox Code Playgroud)

当我编译它时会给出错误.

类封闭的模板参数的默认参数 'bool stack<element_type,container_type>::empty()'

为什么编译器会抱怨,我该如何使它工作?

asc*_*ler 27

您尝试将第二个模板参数的默认参数提供stack两次.默认模板参数,就像默认函数参数一样,只能定义一次(每个翻译单元); 甚至不允许重复完全相同的定义.

只需在定义类模板的开头键入默认参数即可.在那之后,把它留下:

template<typename element_type,typename container_type>
bool stack<element_type,container_type>::empty(){
    return container.empty();
}
Run Code Online (Sandbox Code Playgroud)