【问题标题】:Signature of a template method that returns a nested template gives compile error返回嵌套模板的模板方法的签名会产生编译错误
【发布时间】:2013-04-29 15:58:38
【问题描述】:

我有一个像这样嵌套模板类的模板类

#include <utility>
template<typename K> class Tree23 {

    public:
    template<typename Key> class Node {
       private:
        friend class Tree23<K>;             
        // snip . . .
    };  
    Node<K> root; 
 public:    
     // snip ...            
     std::pair<bool, Node<K> *> Search(K key);
};

我在 Search 方法实现的签名上遇到几个编译错误

template<typename K> 
std::pair<bool, Tree23<K>::Node<K> *> Tree23<K>::Search(K key)
{
    // make sure tree has at least one element    
    if (root == 0) {
          return std::make_pair(false, 0);

    } else {
          return Locate(key, root);
    }
}    

错误对应的行

template<typename K> std::pair<bool, Tree23<K>::Node<K> *> Tree23<K>::Search(K key)

编译错误是:

  Node.h:64:55: error: type/value mismatch at argument 2 in template parameter list for   'template<class _T1, class _T2> struct std::pair'    
  Node.h:64:55: error:   expected a type, got '(Tree23<K>::Node < <expression error>)'    
  Node.h:64:58: error: expected unqualified-id before '>' token    
  Node.h:64:58: error: expected initializer before '>' token

我不清楚如何解决这个问题。任何反馈将不胜感激。

【问题讨论】:

    标签: c++ templates types compilation signature


    【解决方案1】:

    试试这个:

    template<typename K> 
    std::pair<bool, typename Tree23<K>::template Node<K> *> Tree23<K>::Search(K key)
    //              ^^^^^^^^            ^^^^^^^^
    {
        // make sure tree has at least one element
        if (root == 0) {
              return std::make_pair(false, 0);
    
        } else {
              return Locate(key, root);
        }
    }
    

    还有check this out,为什么这是必要的。

    【讨论】:

    • 感谢您的回复。添加 typename 导致一组不同的错误: Node.h:64:67: error: template argument 2 is invalid Node.h:64:69: error: prototype for int Tree23&lt;K&gt;::Search(K) does not match类中的任何Tree23&lt;K&gt; Node.h:57:44: 错误:候选人是:std::pair&lt;bool, Tree23&lt;K&gt;::Node&lt;K&gt;*&gt; Tree23&lt;K&gt;::Search(K) 编译器现在认为原型是int Tree23&lt;K&gt;::Search(K)
    • 谢谢。我错误地只添加了类型名,比如std::pair&lt;bool, typename Tree23&lt;K&gt;::Node&lt;K&gt; *&gt;,而不是添加模板,比如std::pair&lt;bool, typename Tree23&lt;K&gt;::template Node&lt;K&gt; *&gt;
    • 将 typedef 添加到 typedef Node&lt;K&gt; nodeType; 的类 Tree23 中,将函数签名缩短为 template&lt;typename K&gt; std::pair&lt;bool, typename Tree23&lt;K&gt;::nodeType *&gt; Tree23&lt;K&gt;::Search(K key) {//... }
    • 您真的需要Node 作为模板吗?您可以在 Tree23 模板中嵌套一个 class Node { ... };。当然,只有在 Node 中的 Key 与 Tree 中的 K 始终相同时,这才有效。
    猜你喜欢
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    相关资源
    最近更新 更多