【发布时间】:2021-06-03 04:07:55
【问题描述】:
当我编写如下 C++ 代码时:
#include <iostream>
#include <memory>
#include <functional>
template <typename T>
struct Node
{
T data;
std::shared_ptr<T> left;
std::shared_ptr<T> right;
Node(const T& data)
:data(data)
{}
};
template <typename T>
void PreorderTraverse(std::shared_ptr<Node<T>>& root,
std::function<void(std::shared_ptr<Node<T>>&)> callback = nullptr)
{
callback(root);
}
int main()
{
using namespace std;
auto root = make_shared<Node<int>>(5);
// Why must write template type explicitly?
//PreorderTraverse(root, [](shared_ptr<Node<int>>& node)->void { cout << node->data << endl; });
PreorderTraverse<int>(root, [](shared_ptr<Node<int>>& node)->void { cout << node->data << endl; });
//...
return 0;
}
我不能像这样调用 PreorderTraverse 来执行
PreorderTraverse(root, [](shared_ptr
& node)->void { cout data
也许编译器无法推断实例类型,那么我应该如何修改此代码以使编译器能够像上面的评论一样推断调用“PreorderTraverse”?
【问题讨论】:
-
对不起,我有一些错字。执行 -> 形式。大声笑