模板化递归函数的语法是什么

What is the syntax to a templated recursive function?

本文关键字:语法 是什么 递归函数      更新时间:2023-10-16

这让我急转弯。作为一个自制的练习,我想在类中模板化一个递归调用。在.h文件中,我有:

template <typename T1> 
    class BinaryTree 
    {
    public:
        BinaryTree(T1 element);
        ~BinaryTree();
    BinaryTree* addLeftLeaf(BinaryTree<T1>* node);

等等。。。

然后在.cpp 中

template <typename T1> BinaryTree* BinaryTree<T1>::addLeftLeaf(BinaryTree<T1>* node)
{
    return node;
}

我尝试了很多想法,但到目前为止什么都没有。只是类似错误C2955的错误:"BinaryTree":使用类模板需要模板参数列表

如有任何建议,我们将不胜感激。

感谢

标记

在源文件中,您需要指定BinaryTree<T1>,而不仅仅是BinaryTree。即

template <typename T1>
BinaryTree<T1>* BinaryTree<T1>::addLeftLeaf(BinaryTree<T1>* node)
{
    return node;
}

在类/结构体中,只能引用没有参数列表的模板。


还要注意,通常在.cpp文件中使用非专用模板是个坏主意,因为这意味着人们将无法隐式实例化它们(如果没有#include.cpp)。

根据经验,.cpp中应该只包含专门的模板。非专用模板应存在于.h中。

如果你知道自己在做什么,并计划手动实例化模板,那么一定要把主体放在.cpp中,但通常人们不会这么做

.cpp文件中不能有模板函数定义,它必须在.h文件中:)

此外,Peter Alexander认为需要在源代码中编辑该函数定义是正确的,但我将把这留给他的回答:)

返回类型不完整,还需要模板参数。