简体   繁体   中英

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? And why it interpreted the node as 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& ?

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. If you want to call the latter, qualify the call:

return mynamespace::apply<GreaterThan>(Node(this), node);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM