Search code examples
c++templatespass-by-referencestringstream

Passing a object member to a template function expecting an integer


I have been reading and reading posts asking similar questions but my doubts persists.

So I have a class like this:

class Instruction{
public:
    unsigned int getAddress();
    uint32_t getValue();
private:
    unsigned int address;
    uint32_t value;
}


Then I need to convert a decimal to hexadecimal an write it to a string. I saw this question so I took the function in the answer and put it my Utils.hpp class like this:

Utils.hpp

class Utils{
public:
    ...
    static template< typename T > static std::string toHex( T &i );
}


Utils.cpp

template< typename T >
std::string toHex( T &i ){
    std::stringstream stream;
    stream  << "0x" << std::setfill ('0') << std::setw(sizeof(T)*2)
            << std::hex << i;
    return stream.str();
}
std::string Utils::toHex<unsigned int>();
std::string Utils::toHex<uint32_t>();


On main I have this:

std::stringstream stream;

Instruction *newInstruction = new Instruction(addr, inst); // this attributes the parameters

stream  << Utils::toHex(newInstruction->getAddress()) << " "
        << Utils::toHex(newInstruction->getValue()) << endl;

And I get the following compiling errors:

main.cpp: In function 'int main(int, char**)':
main.cpp:39: error: no matching function for call to 'Utils::toHex(unsigned int)'
Utils.hpp:16: note: candidates are: static std::string Utils::toHex(T&) [with T = unsigned int]
main.cpp:41: error: no matching function for call to Utils::toHex(uint32_t)'
Utils.hpp:16: note: candidates are: static std::string Utils::toHex(T&) [with T = unsigned int]
make: *** [main.o] Error 1

I really need help to figure out how I can make this work, because I am relatively new to this stuff.


Thank you in advance!


Solution

  • You should make toHex accept const reference to T: toHex(const T&). Otherwise you cannot pass a temporary to it, whereas the result of function call is a temporary.

    Also note that the question/answer you are referring to is not working with references at all, it has

    std::string int_to_hex( T i )