【问题标题】:Templated class: unable to match function definition to an existing declaration模板类:无法将函数定义与现有声明匹配
【发布时间】:2013-05-10 22:15:07
【问题描述】:

使用 MSVC++ 2010,在其声明块之外定义模板类成员:

template <typename T> class cls {
public:
    template <typename T> void bar(T x);
};
template <typename T> void cls<T>::bar(T x) {}

产量:

unable to match function definition to an existing declaration
1>          definition
1>          'void cls<T>::bar(T)'
1>          existing declarations
1>          'void cls<T>::bar(T)'

为什么?

【问题讨论】:

    标签: c++ class templates


    【解决方案1】:

    您需要两个模板声明,因为每个构造都适用于不同的模板参数:

    template <typename P>
    template <typename T>
    void cls<P>::bar(T x) {}
    

    但在我看来,bar 根本不需要模板化。改用这个:

    template <typename T>
    class cls
    {
        public:
            void bar(T x);
    };
    
    template <typename T> void cls<T>::bar(T x) {}
    

    【讨论】:

    • 现在我得到llegal use of explicit template arguments
    • 在您的示例中,您使用了两次template &lt;typename T&gt;。这就是导致错误的原因。将类型名称更改为其他名称。
    • 您不应该为bar 显式编写模板参数,它被解析为部分特化。
    【解决方案2】:

    如果您打算让bar 成为会员模板,那么您需要这个:

    template <typename T> class cls {
    public:
        template <typename U> void bar(U x);
    };
    
    template<typename T>
    template<typename U>
    void cls<T>::bar(U x) { }
    

    注意,成员的模板参数不能遮蔽类模板参数,所以我把它改成了U

    【讨论】:

      猜你喜欢
      • 2016-05-11
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多