在支持多种类型的宏中使用printf
using printf in a macro supporting multiple types
我有一个宏:
#define assert_cmp(a, cmp, b)
if(!((a) cmp (b))) {
std::cerr << "Assertion failed: " << a << " " << #cmp << " " << b << std::endl;
assert((a) cmp (b));
}
(是的,我也许应该围绕它做do { ... } while(0)
...(
然后我可以使用它,例如:
void f(int a) {
assert_cmp(a, <=, 42);
// ...
}
正常工作。但是,现在,我也想对一些CUDA代码使用相同的宏,并且我只能在那里使用printf
。(CUDA与问题并不相关,只是我必须使用printf
。(
如何将宏转换为使用printf
而不是std::cerr
?这并不是那么简单,因为参数 a
和 b
可以是任何类型的(尽管我们现在只关心数字类型是可以的(。
也许喜欢:
#define assert_cmp(a, cmp, b)
if(!((a) cmp (b))) {
printf("Assertion failed: ");
printf(_format_for_type(a), a);
printf(" " #cmp " ");
printf(_format_for_type(b), b);
printf("n");
assert((a) cmp (b));
}
template<typename T>
const char* _format_for_type(const T&);
template<> const char* _format_for_type(const int&) { return "%i"; }
template<> const char* _format_for_type(const float&) { return "%f"; }
...
如何翻译宏以使用printf代替std :: cerr?
这是一般不可能做的,因为printf
仅支持有限的指定符和长度子分类器计数。换句话说,可以用operator<<
打印类型,但不能用printf
。
您可以做std::ostringstream ss; ss << stuff; printf("%s", ss.str());
。
也许喜欢:
是的,这样,这是一种很好的方法,可以控制和在编译时检测到任何问题。我认为创建格式字符串的价值没有,只需打印值即可。我不会创建格式字符串,而只是输出值,这将允许为自定义类型创建过载。
template<typename T> void myprint(const T&);
template<> void myprint(const int& v) { printf("%i", v); }
template<> void myprint(const float& v) { printf("%f", v); }
// custom types
class MyData {
int a;
int b;
template<typename T> friend void myprint(const T &v);
};
template<> void myprint(const MyData& v) {
printf("%d %d", v.a, v.b);
}
#define assert_cmp(a, cmp, b)
... myprint(a); ...
相关文章:
- 编译时未启用intel oneApi CUDA支持
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用CMake检测支持的C++标准
- 为什么istream不支持右值提取
- 当我编译webrtc服务器时,Windows上只支持clang-cl
- 扩展光电二极管探测器以支持多个传感器
- MSVC是否支持C++11样式的属性而不是__declspec
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 内联程序集printf将整数解释为地址
- 在使用GPU支持编译Tensorflow时,会遇到CUDA_TOOLKIT_PATH未绑定变量
- 为什么mpfr_printf与十六进制浮点(%a转换说明符)的printf不同
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- C++ Setter/Getter,cout 工作,printf 失败
- 错误:(-210:不支持的格式或格式组合)功能'create'中的硬件视频解码器不支持视频源
- 哪个C++规范开始支持 std::vector
- Printf 命令不打印时添加了查找常见除数的新代码
- 如何检测VS C++编译器是否支持C++11?
- SIGSEGV, 分段错误. 而 printf() 数组索引的值
- 为什么在包含iostream时可以使用printf()?
- 在支持多种类型的宏中使用printf