对于模板类声明:
enum class traversal_order {PREORDER, INORDER, POSTORDER};
template<typename T1>
class node{
//public and private members
};
template<typename T1, typename T2>
class tree{
//rest of template
public:
using sp2node_cont = vector<shared_ptr<node<T1>>>;
using r_iter_sp2node_cont = typename vector<shared_ptr<node<T1>>>::iterator&;
public:
tree(T2 const&, size_t);
void traversal_tree(traversal_order);
//rest of template
private:
sp2node_cont impl_tree;
};
以下是模板方法的定义:
template<typename T1, typename T2>
tree<T1,T2>::traverse_tree(traversal_order D){
switch(D){
case PREORDER:
{
function<void(r_iter_sp2node_cont,r_iter_sp2node_cont)>
print_preorder = [&] (r_iter_sp2node_cont begin,
r_iter_sp2node_cont end
){
//rest of the definition
print_preorder(std::next(begin), end);
};
print_preoder(impl_tree.begin(), impl_tree.end());
break;
}
}
}
在构造树对象后,编译器在从main()调用时对std::function print_preorder()
的递归调用生成以下错误,如下所示:
std::array<string,25> A;
//rest of the code
tree<string, decltype(A)> a_tree(A,A.size());
a_tree.traverse_tree(traversal_order::PREORDER);
1 In file included from main.cpp:1:
2 ./bt.hpp:306:21: error: no matching function for call to object of type 'function<void (r_iter_sp2node_cont, r_iter_sp2node_cont)>' (aka 'function<void (__wrap_iter<std::__1::shared_ptr<node<std::__1:: basic_string<char> > > *> &, __wrap_iter<std::__1::shared_ptr<node<std:: __1::basic_string<char> > > *> &)>')
3 print_preorder(next(begin), end);
4 ^~~~~~~~~~~~~~
5 main.cpp:23:12: note: in instantiation of member function 'tree<std::__1:: basic_string<char>, std::__1::array<std::__1::basic_string<char>, 25> >:: traverse_tree' requested here
6 a_tree.traverse_tree(traversal_order::PREORDER);
7 ^
8 /Library/Developer/CommandLineTools/usr/include/c++/v1/functional:1667:9: note: candidate function not viable: expects an l-value for 1st argument
9 _Rp operator()(_ArgTypes...) const;
10 ^
11 1 error generated.
我不确定如何解决此错误。有什么建议吗?
答案 0 :(得分:2)
您的问题就在这一行
using r_iter_sp2node_cont = typename vector<shared_ptr<node<T1>>>::iterator&;
您已将r_iter_sp2node_cont
定义为对迭代器的引用。
所以print_preorder
的签名是
print_preorder(vector...::iterator&, vector...::iterator&)
但是当你打电话时
print_preorder(impl_tree.begin(), impl_tree.end());
向量begin()
和end()
的方法返回iterator
个对象。您不能将这些成员函数返回的临时iterator
对象传递给期望引用迭代器iterator&
的函数。
您应该从定义&
类型中删除r_iter_sp2node_cont
。
PS。
您的代码可以在具有扩展名的MSVC下编译,临时对象可以传递给函数,期望引用对象void foo(anObject&)
。