模板化递归函数的语法是什么
What is the syntax to a templated recursive function?
这让我急转弯。作为一个自制的练习,我想在类中模板化一个递归调用。在.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认为需要在源代码中编辑该函数定义是正确的,但我将把这留给他的回答:)
返回类型不完整,还需要模板参数。
相关文章:
- C++避免重复声明的语法是什么
- 使用基类指针调用基类的值构造函数的语法是什么?
- 这行/语法是什么意思?
- 初始化对象以在 C++08 中作为参数传递的首选语法是什么?
- 将引用绑定到指针的语法是什么?(各种)
- 这个typedef和转换运算符语法是什么意思
- 此语法是什么意思.(::*).
- 将显式指定的函数模板重载作为模板参数传递的正确语法是什么?
- 使用 pybind11 绑定 typedef 类型的正确语法是什么?
- 将此类传递给引用的正确语法是什么?
- 带有约束的可变参数模板的'requires'表达式的语法是什么?
- 在TensorFlow C++中用于feed_dict的语法是什么?
- 调用模板化类内的枚举类枚举器的正确语法是什么
- 返回没有 typedef 的成员函数指针的语法是什么?
- 将强制转换运算符重载到 std::map 的正确语法是什么
- 这种增量语法是什么意思
- 返回结构的方法的正确语法是什么
- C 中的(*)语法是什么意思
- 堆栈(int = 10),这个语法是什么意思(C++)
- variadic模板阵列参考参数的语法是什么?