【问题标题】:C++ class templates argument invalidC++ 类模板参数无效
【发布时间】:2014-12-10 18:07:44
【问题描述】:

我想像这样定义一个二叉树类模板:

template<typename Any>
class tree {
    public:
        struct treeNode {
            Any &_data;
            treeNode *_left, *_right;
            treeNode(const Any &data, treeNode *left = nullptr,
                     treeNode *right = nullptr) :
                     _data(data), _left(left), _right(right) {
            }
        };
    // ...
        std::vector<treeNode *> lookfor(
                const treeNode *, const std::function<bool(const Any &)> &) const;
};

// ↑ tree.h
// ↓ tree.cpp

template<typename Any>
std::vector<tree::treeNode *> tree<Any>::lookfor(
        const treeNode *x, const std::function<bool(const Any &)> &cmp) const {
    // ...
}

然后g++不高兴了,告诉我这个:

tree.cpp:129:29: error: template argument 1 is invalid
 std::vector<tree::treeNode *> tree<Any>::lookfor(
                             ^
tree.cpp:129:29: error: template argument 2 is invalid
tree.cpp:129:31: error: prototype for ‘int tree<Any>::lookfor(const tree<Any>::treeNode*, const std::function<bool(const Any&)>&) const’ does not match any in class ‘tree<Any>’
 std::vector<tree::treeNode *> tree<Any>::lookfor(
                               ^
In file included from tree.cpp:1:0:
tree.h:88:33: error:                 std::vector<tree<Any>::treeNode*> tree<Any>::lookfor(const tree<Any>::treeNode*, const std::function<bool(const Any&)>&) const
         std::vector<treeNode *> lookfor(
                                 ^

所以我想知道为什么会发生这种情况以及如何修复这个错误。

我不擅长英语,这是我第一次在 statckoverflow 上提问,如果我犯了任何错误,请告诉我:)

【问题讨论】:

标签: c++ class templates stl


【解决方案1】:

代码:

std::vector<tree::treeNode *> tree<Any>::lookfor

引用树,它是一个模板,没有模板参数。它应该是这样的:

std::vector<typename tree<Any>::treeNode *> tree<Any>::lookfor

此外,由于这些是模板,因此您不应该有树的 .cpp 文件,这也会导致问题。

【讨论】:

  • std::vector&lt;typename tree&lt;Any&gt;::treeNode *&gt; tree&lt;Any&gt;::lookfor
  • 对!但请注意,这在 C++11 中不再需要:open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#409 此外,在 gcc 4.3.4 及更高版本中也不需要:gcc.gnu.org/bugzilla/show_bug.cgi?id=9634
  • g++ -std=c++11 (4.8.2) 需要类型名
  • @MatiasFG, typename 仍然需要依赖名称,您引用的链接不会改变这一点。 tree&lt;Any&gt; 显然是依赖的,因为Any 是一个模板参数。
  • 谢谢。我将 .cpp 中的代码移到了头文件中,它工作了 XD
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
  • 1970-01-01
  • 2017-10-10
  • 2013-03-09
相关资源
最近更新 更多