我正在实现一个2 3树,它有一个带有仿函数的级别顺序遍历方法。 运营商。 tree23代码基本上是这样的:
template<class Key, class Value> class tree23 {
public:
class Node23 {
friend class tree23<Key, Value>;
public:
// snip...
friend std::ostream& operator<<(std::ostream& ostr, const Node23& node23)
{
// snip... outputs the keys and values of node23 to ostr.
}
private:
Node23 *parent;
std::array<Key, 2> keys;
std::array<Value, 2> values;
std::array<std::unique_ptr<Node23>, 3> children;
int totalItems; // either TwoNodeItems or ThreeNodeItems
// snip...
};
template<typename Functor> void levelOrderTraverse(Functor f) const noexcept;
// snip...
};
级别顺序遍历调用仿函数的函数调用操作符,并传递两个参数。
template<class Key, class Value> template<typename Functor> \
void tree23<Key, Value>::levelOrderTraverse(Functor f) const noexcept
{
std::queue< std::pair<const Node23*, int> > queue;
Node23 *proot = root.get();
if (proot == nullptr) return;
auto initial_level = 1; // initial, top level is 1, the root.
queue.push(std::make_pair(proot, initial_level));
while (!queue.empty()) {
std::pair<const Node23 *, int> pair_ = queue.front();
const Node23 *current = pair_.first;
int current_tree_level = pair_.second;
// invokes functor's operator()(const Node23&, int)?
f(*current, current_tree_level);
if (!current->isLeaf()) {
for(auto i = 0; i < current->getChildCount(); ++i) {
queue.push(std::make_pair(current->children[i].get(), current_tree_level + 1));
}
}
queue.pop();
}
}
仿函数很简单:
class levelOrderPrinter {
private:
// snip...
public:
levelOrderPrinter(std::ostream& ostr_lhs, int depth);
levelOrderPrinter(levelOrderPrinter&);
levelOrderPrinter(const levelOrderPrinter&);
template<class Key, class Value>
void operator()(const typename tree23<Key, Value>::Node23& node,
int current_level) noexcept;
};
template<class Key, class Value>
void levelOrderPrinter::operator()(const typename tree23<Key, Value>::Node23& node,
int current_level) noexcept
{
// Did level change?
if (level != current_level) {
level = current_level;
ostr << "\n\n" << "level = " << level;
// Provide some basic spacing to tree appearance.
std::size_t num = tree_depth - level + 1;
std::string str( num, ' ');
ostr << str;
}
ostr << node;
}
答案 0 :(得分:2)
如果你改变你的函数调用操作符的声明:
template<class Node>
void levelOrderPrinter::operator()(const Node& node, int current_level) noexcept
然后编译器将能够推导出Node
的类型。
在原始代码中:
template<class Key, class Value>
void levelOrderPrinter::operator()(const typename tree23<Key, Value>::Node23& node,
int current_level) noexcept
编译器无法推断出类型Key
或Value
,因为tree23<Key, Value>::Node23
是<{1}}和Key
的非推断上下文 {1}}(§14.8.2.5),强制您使用显式函数模板调用语法。
答案 1 :(得分:1)
更改此行
f(*current, current_tree_level);
方法
template<class Key, class Value> template<typename Functor> \
void tree23<Key, Value>::levelOrderTraverse(Functor f) const noexcept
是
f.template operator()<Key, Value>(*current, current_tree_level);
摆脱了“无法推断模板参数”的错误。它不是很漂亮,但它现在可以编译。
答案 2 :(得分:1)
Node23是一种嵌套类型,其封闭类型的模板参数无法轻易推断出来。因此,您必须通过template operator()
明确指定它们。