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

C++ 类封闭的模板参数的默认参数,c++,templates,C++,Templates,代码: 模板 类堆栈 { 公众: 堆栈(){} 模板 堆栈(CT临时):容器(临时开始(),临时结束()){} bool empty(); 私人: 集装箱(u型集装箱),; }; 模板 bool stack::empty() { 返回容器.empty(); } 当我编译时,它给出了错误 类封装的模板参数的默认参数'bool stack::empty()' 为什么编译器会抱怨,我该如何使它工作?默认参数在语法上是类的默认参数,并且仅在类声明时才有意义 如果你调用这个函数 template <

代码:

模板
类堆栈
{
公众:
堆栈(){}
模板
堆栈(CT临时):容器(临时开始(),临时结束()){}
bool empty();
私人:
集装箱(u型集装箱),;
};
模板
bool stack::empty()
{
返回容器.empty();
}
当我编译时,它给出了错误

类封装的模板参数的默认参数
'bool stack::empty()'


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

默认参数在语法上是类的默认参数,并且仅在类声明时才有意义

如果你调用这个函数

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();
}
stack().empty();
在类名的站点上只有模板参数,在模板类声明处已经为其提供了默认参数

只需从函数定义中删除默认参数即可解决此问题:

stack<foo,bar>().empty();
模板
bool stack::empty(){
返回容器.empty();
}

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

只需在定义类模板的开头键入默认参数。之后,请将其忽略:

template<typename element_type,typename container_type>
bool stack<element_type,container_type>::empty(){
    return container.empty();
}
模板
bool stack::empty(){
返回容器.empty();
}

这真的是完整的错误消息吗?看起来好像缺少了什么东西…@TimoGeusch:当用g++和
--std=c++0x
编译时,确实是这样。虽然它实际上是正确的,但乍一看并没有多大帮助:/
template<typename element_type,typename container_type>
bool stack<element_type,container_type>::empty(){
    return container.empty();
}