将对象成员传递给期望为整数的模板函数

Passing a object member to a template function expecting an integer

本文关键字:整数 函数 期望 成员 对象      更新时间:2023-10-16

我一直在阅读和阅读问类似问题的帖子,但我的疑问仍然存在。

我有一个这样的类:

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


然后我需要将十进制转换为十六进制并将其写入字符串。我看到了这个问题,所以我把答案中的函数放在我的Utils.hpp类中,像这样:

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>();


在main上我有这个:

std::stringstream stream;
Instruction *newInstruction = new Instruction(addr, inst); // this attributes the parameters
stream  << Utils::toHex(newInstruction->getAddress()) << " "
        << Utils::toHex(newInstruction->getValue()) << endl;

,我得到以下编译错误:

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

我真的需要帮助来弄清楚如何才能完成这项工作,因为我对这些东西比较陌生。


提前感谢!

您应该使toHex接受constT: toHex(const T&)的引用。否则不能传递临时对象,而函数调用的结果是临时对象。

还要注意,你所引用的问题/答案根本不使用引用,它有

std::string int_to_hex( T i )

您在函数定义中缺少Utils::前缀,并且如前所述,参考文献中缺少const。更正后的Utils.cpp应该是:

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