【发布时间】:2014-09-20 09:18:11
【问题描述】:
我有一个以整数类型为模板的 C++ 类;类似于
template<typename int_type>
void myClass(int_type a) {
// [...]
}
我现在想用sscanf() 将文件中的数据读入int_type 类型的变量中。为此,我必须指定int_type 的格式。到目前为止,我正在做类似的事情
if(sizeof(int) == sizeof(int_type))
sscanf(buffer, "%d %d", &i, &j);
else if(sizeof(long long) == sizeof(int_type))
sscanf(buffer, "%lld %lld", &i, &j);
else
assert(false);
但这似乎不是处理事情的最佳方式。
还有其他建议吗?
【问题讨论】:
-
最好使用绑定到
std::istringstream的operator<<()的模板版本,而不是sscanf()。 -
sizeof(int) == sizeof(unsigned int),但%d不是unsigned int的正确格式说明符(例如,考虑INT_MAX和UINT_MAX之间的那些数字)。要为不同的类型提供不同的实现,函数重载通常是一个不错的方法。
标签: c++ templates format-specifiers