Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在支持多种类型的宏中使用printf_C++ - Fatal编程技术网

C++ 在支持多种类型的宏中使用printf

C++ 在支持多种类型的宏中使用printf,c++,C++,我有这样一个宏: #define assert_cmp(a, cmp, b) \ if(!((a) cmp (b))) { \ std::cerr << "Assertion failed: " << a << " " << #cmp << " " << b << std::endl; \ assert((a) cmp (b)); \ } #define asse

我有这样一个宏:

#define assert_cmp(a, cmp, b) \
    if(!((a) cmp (b))) { \
        std::cerr << "Assertion failed: " << a << " " << #cmp << " " << b << std::endl; \
        assert((a) cmp (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"; }

...
那很好。然而,现在我想对一些CUDA代码也使用相同的宏,我只能在那里使用
printf
。(CUDA与这个问题并不相关,只是我必须使用
printf

如何将宏转换为使用
printf
而不是
std::cerr
?这并不是那么简单,因为参数
a
b
可以是任何类型(尽管如果我们现在只关心数字类型就可以了)

也许是这样:

#define assert_cmp(a, cmp, b) \
    if(!((a) cmp (b))) { \
        std::cerr << "Assertion failed: " << a << " " << #cmp << " " << b << std::endl; \
        assert((a) cmp (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"; }

...
#定义断言(a,cmp,b)\
如果(!((a)cmp(b)){\
printf(“断言失败:”)\
printf(_格式_用于_类型(a),a)\
printf(“#cmp”)\
printf(_格式_用于_类型(b),b)\
printf(“\n”)\
断言((a)cmp(b))\
}
模板
const char*_格式_用于_类型(const T&);
模板const char*\u格式\u用于类型(const int&){返回“%i”}
模板const char*\u格式\u类型(const float&){返回“%f”}
...

此问题中的任何内容看起来都不像C。您确定标记有用吗?可能是这样的-这种方法有什么问题?顺便说一句,我很确定你可以在CUDA的更高版本中使用IO流。双“#”+双扩展会有帮助吗?(例如)@Yunnosch:我不知道。我想是因为我使用了C风格的宏。虽然我不知道用C++来完成类似的事情(不使它太复杂)。但是也许我们可以把标签去掉。@Swardfish:我还不知道。在写问题时,这是一个自发的想法。我正在努力。但也许其他人知道更好的方法。另外,对于
std::cerr
版本,我得到一些无法调用主机函数的CUDA错误。而且我知道,
printf
在任何情况下都是有效的。