【问题标题】:Templated class method definition syntax模板化类方法定义语法
【发布时间】:2010-11-19 17:25:52
【问题描述】:

类定义:

template<class K, class V,
         unsigned hashFunc(const K&),
         int compFunc(const K&,const K&)=&_compFunc<K> > class X {};

我想在类代码块之外定义一个类方法。像这样:

template<class K, class V,
         unsigned hashFunc(const K&),
         int compFunc(const K&,const K&)=&_compFunc<K> >
X<K, V, hashFunc, compFunc>::X() { }

g++ v.4.4.3 返回

错误:模板的默认参数 包含“X::X()”的类的参数

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

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    您没有为X 声明或定义构造函数。此外,您在尝试的 X::X 定义中重复了默认模板参数。

    这是固定代码,main-ified:

    template<class K, class V,
             unsigned hashFunc(const K&),
             int compFunc(const K&,const K&)=&_compFunc<K> > 
    class X 
    { 
        X();
    };
    
    template<class K, class V,
             unsigned hashFunc(const K&),
             int compFunc(const K&,const K&) >
    X<K, V, hashFunc, compFunc>::X() { }
    
    int main()
    {
    }
    

    【讨论】:

      【解决方案2】:

      您不应该重复默认模板参数:

      template<class K, class V,
               unsigned hashFunc(const K&),
               int compFunc(const K&,const K&)>
      X<K, V, hashFunc, compFunc>::X() { /* ... */ }
      

      正如 John Dibling 所指出的,类 X 显然也必须声明构造函数,但为了清楚起见,我假设代码已被删除。

      【讨论】:

        猜你喜欢
        • 2017-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多