【问题标题】:Passing a object member to a template function expecting an integer将对象成员传递给需要整数的模板函数
【发布时间】:2015-07-09 13:36:37
【问题描述】:

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

所以我有这样的课程:

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


然后我需要将十进制转换为十六进制并将其写入字符串。我看到了this question,所以我把答案中的函数放在了我的 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>();


我主要有这个:

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

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


提前感谢您!

【问题讨论】:

  • 您阅读了哪些帖子?我记得的所有关于该主题的人都给出了相同的答案!

标签: c++ templates pass-by-reference stringstream


【解决方案1】:

您应该让toHex 接受constT 的引用:toHex(const T&amp;)。否则你不能给它传递一个临时的,而函数调用的结果是一个临时的。

另请注意,您所指的问题/答案根本不适用于参考,它有

std::string int_to_hex( T i )

【讨论】:

    【解决方案2】:

    您在函数定义中缺少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();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多