[英]C++ argument should be passed by value, but compiler sees it as reference
So its very weird behaviour which I do not understand. 因此,这是我不理解的非常奇怪的行为。 I have:
我有:
template <typename T>
Node Node::apply() {
return ptr->graph->derived_node(std::make_shared<T>(ptr->graph, this));
}
template <typename T>
Node apply(Node parent1, Node parent2){
GraphInPtr graph = parent1.ptr->graph;
return graph->derived_node(std::make_shared<T>(graph, parent1, parent2));
}
template <typename T>
Node apply(NodeVec parents){
GraphInPtr graph = parents[0].ptr->graph;
return graph->derived_node(std::make_shared<T>(graph, parents));
}
I also have this: 我也有这个:
Node gt(Node node1, Node node2){
return apply<GreaterThan>(node1, node2);
}
However, this here compiles with an error: 但是,这在编译时会出现错误:
Node Node::gt(Node node) {
return apply<GreaterThan>(Node(this), node);
}
The error is: 错误是:
error: no matching function for call to ‘metadiff::Node::apply(metadiff::Node, metadiff::Node&)’
return apply<GreaterThan>(Node(this), node);
note: candidate is:
note: template<class T> metadiff::Node metadiff::Node::apply()
Node Node::apply()
So for some reason it is trying to call the Node::apply()
instead of the apply(Node node1, Node node2)
, but I don't understand why? 因此由于某种原因,它试图调用
Node::apply()
而不是apply(Node node1, Node node2)
,但是我不明白为什么? And why it interpreted the node as Node&
? 为什么将节点解释为
Node&
?
Interestingly enough this worked: 有趣的是,它起作用了:
Node Node::gt(Node node) {
// return apply<GreaterThan>(Node(this), node);
GraphInPtr graph = ptr->graph;
return graph->derived_node(std::make_shared<GreaterThan>(graph, this, node));
}
Nevertheless, I'm very curious what is going on?! 不过,我很好奇发生了什么事!
And why it interpreted the node as
Node&
?为什么将节点解释为
Node&
?
That's a red herring. 那是一条红鲱鱼。 It's the compiler's way of showing the value category of the second argument (which is an lvalue, so
&
). 这是编译器显示第二个参数的值类别的方法(它是一个左值,所以
&
)。
Your actual problem is that in a member function, the class member Node::apply
hides the namespace-scope function templates of the same name. 您的实际问题是在成员函数中,类成员
Node::apply
隐藏了具有相同名称的名称空间范围函数模板。 If you want to call the latter, qualify the call: 如果要呼叫后者,请限定呼叫:
return mynamespace::apply<GreaterThan>(Node(this), node);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.