Question

I have chained methods like that:

PureCommand Hasher::nameToPure(CommandName& commandName) {
    return this->commandHash.find(commandName).value();
}
ByteCommand Hasher::nameToByte(CommandName& commandName) {
    return this->pureToByte(this->nameToPure(commandName));
}

The 2nd method is passing commandName which is wrong type as the 1st method needs reference, not an object. Then I've tried this:

ByteCommand Hasher::nameToByte(CommandName& commandName) {
    return this->pureToByte(this->nameToPure(*&commandName));
}

as stated here: How to cast/convert pointer to reference in C++ - because &commandName gives me pointer... but it's passing an object again. What am I doing the silly way? As probably it's something trivial...

Was it helpful?

Solution

There is nothing wrong with the original code. A reference can bind to an object.

(And in fact, no expression ever has a reference type. Expressions can be lvalues, xvalues, or prvalues, and commandName here is an lvalue, so an lvalue reference can bind to it.)

OTHER TIPS

Your code has no problem. But you should instead pass the const reference, Since you are not really modifying the value of commandName.

 PureCommand Hasher::nameToPure(const CommandName& commandName) {
    return this->commandHash.find(commandName).value();
}
ByteCommand Hasher::nameToByte(const CommandName& commandName) {
    return this->pureToByte(this->nameToPure(commandName));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top