【问题标题】:default argument for template parameter for class enclosing封闭类的模板参数的默认参数
【发布时间】:2013-06-12 16:57:15
【问题描述】:

代码:

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();
}

当我编译时它给出了错误。

包含'bool stack&lt;element_type,container_type&gt;::empty()'的类的模板参数的默认参数

为什么编译器会抱怨,我怎样才能让它工作?

【问题讨论】:

  • 这真的是完整的错误信息吗?好像少了点什么……
  • @TimoGeusch:使用 g++ 和 --std=c++0x 编译时确实如此。虽然实际上是正确的,但乍一看并不是很有帮助:/

标签: c++ templates


【解决方案1】:

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

只需在定义类模板的开头键入默认参数即可。之后,将其保留:

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

【讨论】:

    【解决方案2】:

    按照语法,默认参数是类的默认参数,它只在类声明时才有意义。

    如果你要调用那个函数...

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

    您只有类名站点上的模板参数,您已经在模板类声明时为其提供了默认参数。

    您可以通过简单地从函数定义中删除默认参数来解决该问题:

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

    【讨论】:

      猜你喜欢
      • 2016-11-09
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      相关资源
      最近更新 更多