模板参数的格式规范
format specification for template parameters
我有一个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);
但这似乎不是处理事情的最佳方式。
还有其他建议吗?
您可以使用类和专业化:
template <typename T> struct scanf_format;
template <> struct scanf_format<int>
{
static constexpr const char* format = "%d";
static constexpr const char* format2 = "%d %d";
};
template <> struct scanf_format<long long>
{
static constexpr const char* format = "%lld";
static constexpr const char* format2 = "%lld %lld";
};
然后像一样使用
template <typename T>
void my_scanf(const char* buffer, T&a, T&b)
{
sscanf(buffer, scanf_format<T>::format2, &a, &b);
}
但更简单的方法是使用operator >>
template <typename T>
void my_scanf2(const char* buffer, T&a, T&b)
{
std::stringstream ss(buffer);
ss >> a >> b;
}
实例
相关文章:
- C++fmt库,只使用格式说明符格式化单个参数
- clang 格式堆叠所有 if 语句参数,如果它们太长
- clang 格式:始终断开所有参数,每行一个
- 当超出列时,clang格式强制每个参数/参数拥有自己的行?
- 中断长代码 snprintf 格式和参数
- 使用宏定义打印格式参数
- 查找可变参数列表的字符串格式指定符
- 保留短 lambda 用作函数的中间参数,使用 clang 格式保持不变
- sscanf 格式参数不起作用
- sscanf_s:格式字符串"%d"需要类型为"int *"的参数,但可变参数 4 的类型为"WORD *"
- 格式“%lf”期望“ double *”类型的论点,但参数2具有“ poly term **”类型
- 警告:格式"%d"需要类型为"int*"的参数,但参数5的类型为"in
- C4477: 'fprintf' :格式字符串 '%s' 需要类型为"char *"的参数,但可变参数 1 的类型为"int *"
- 执行带有参数的 .bat 文件并以 C++ 格式读取控制台输出
- 警告:格式"%5f"需要类型"double",但参数3的类型为"int
- 如何将 GCC 的 printf 格式属性与 C++11 可变参数模板一起使用?
- format不是字符串文字,也没有格式参数[-Wformat security]
- 如何在c++中传递变量Sprintf第二(格式)参数
- c++ fprintf函数调用中格式/参数类型不匹配的可能后果是什么?
- 格式化不是字符串字面值,也没有格式参数