【问题标题】:Template method of the template class模板类的模板方法
【发布时间】:2020-12-08 20:42:34
【问题描述】:

我的头文件中有这个声明:

template<class T>
class list {
protected:
    struct Node{...}
public:
...
template<typename Predicate>
Node* find_if(const Predicate& pred);
...
};

在类声明之后我有 find_if 方法定义(在同一个文件中):

template<class T, typename Predicate>
typename list<T>::Node* list<T>::find_if(const Predicate& pred) {...}

但 MSVC 编译器“无法将函数定义与现有声明匹配” 为什么我的方法定义是错误的? 感谢帮助

【问题讨论】:

  • 必须是template&lt;class T&gt; template &lt;typename Predicate&gt; typename list&lt;T&gt;::Node* list&lt;T&gt;::find_if(const Predicate&amp; pred) {...} 即您必须在外部定义中重复嵌套模板。

标签: c++ templates


【解决方案1】:

对于嵌套模板和外部定义,OP的做法是不正确的。

正确的是:

template<class T>
template <typename Predicate>
typename list<T>::Node* list<T>::find_if(const Predicate& pred) { ... }

即每个模板必须单独编写。

演示:

template<class T>
class list {
protected:
    struct Node { };
public:

  template<typename Predicate>
  Node* find_if(const Predicate& pred);

};

#if 0 // OPs attempt: Syntax error.

template<class T, typename Predicate>
typename list<T>::Node* list<T>::find_if(const Predicate& pred);

#else // Correct:

template<class T>
template <typename Predicate>
typename list<T>::Node* list<T>::find_if(const Predicate& pred) { return nullptr; }

#endif // 0

int main()
{
  list<int> intList;
}

Live Demo on coliru

【讨论】:

    【解决方案2】:

    判断你的定义不正确的简单方法是你没有声明任何带有两个参数的模板。正确的语法是

    template <class T>
    template <typename Predicate>
    typename list<T>::Node* list<T>::find_if(const Predicate& pred) {}
    

    【讨论】:

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