我想在模板函数中添加调试,但是不考虑重新编辑整个代码。
有没有人能够
#define theFunction<T>(size) _theFunction<T>(size, __FILE__, __LINE__)
template<class T> T* _theFunction(int size, string file, int line)
{
if (fails) {
printf("theFunction failed called at line %i on %s ", line, file);
}
}当然,在宏声明中返回'<‘是意外的。有没有什么技巧可以让它工作呢?
发布于 2020-12-14 23:04:22
可能是这样的东西(未经过测试):
struct TheFunctionHelper {
std::string file;
int line;
template<typename T>
T* invoke(int size) {
return _theFunction<T>(size, file, line);
}
};
#define theFunction TheFunctionHelper{__FILE__, __LINE__}.invoke发布于 2020-12-14 23:04:47
在编写宏时,使用编译器标志很有帮助,它允许您在预处理后看到输出。对于gcc来说,这是-E看到的:
#define theFunction(T,size) _theFunction<T>(size, __FILE__, __LINE__)
theFunction(int,42);扩展为:
_theFunction<int>(42, "./example.cpp", 5);将int作为参数传递给theFunction(int,42)看起来有点奇怪,但是一旦您决定使用宏,事情就变得很奇怪;)。
还要注意,正如在评论中提到的,C++20有std::source_location,它消除了C++中需要使用宏的最后一个角落之一。
https://stackoverflow.com/questions/65291188
复制相似问题