将对象成员传递给期望为整数的模板函数
Passing a object member to a template function expecting an integer
我一直在阅读和阅读问类似问题的帖子,但我的疑问仍然存在。
我有一个这样的类:
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
接受const对T
: 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();
}
相关文章:
- 添加存储在向量中的大整数的函数出现问题
- C++模板函数,用于比较任何无符号整数和有符号整数
- 使用英特尔内联函数将打包的 8 位整数乘以浮点数向量
- 整数键映射到头文件中的成员函数指针
- 如何使此递归函数从给定的起始位置返回最小的整数?
- 反转整数的一部分(一半)的函数
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 您将如何连接"on the fly"文本+整数并将其传递给函数?
- constexpr log10 整数函数
- 如何检测除整数以外的任何内容是否传递给我的类构造函数?
- 如何使用 binary_search STL 函数在嵌套类中搜索整数?
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- C++:为什么我的掷骰子函数在掷骰子数量时只返回偶数整数?
- 从函数参数 [C++] 复制整数数组
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 模函数,避免C++整数溢出
- 通过规范化 // 函数来调整数组
- 我想使用 std::stoi 函数在 cpp 中将字符串转换为整数,因为我想在字符串中找到不同数字的总和(在下级酶中)
- 没有返回值的整数函数