将调用者__FILE__ __LINE__传递到函数而不使用宏 [英] Passing the caller __FILE__ __LINE__ to a function without using macro

查看:162
本文介绍了将调用者__FILE__ __LINE__传递到函数而不使用宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯了:

  class Db {
_Commit(char * file,int line) {
Log(Commit from%s:%d,file,line);
}
};

#define Commit()_Commit(__ FILE__,__LINE__)

大问题是我重新定义了 Commit 这个词,在一个400k行的应用程序框架中,这是一个问题。我不想使用像 DbCommit 这样的特定词:我不喜欢像 db-> DbCommit(),或者手动在任何地方传递值: db->提交(__ FILE__,__LINE __)是最差的。



解决方案

行信息,你宁愿不使用宏,对吧?



在一天结束时,它不能在C ++中完成。无论你选择什么机制 - 内联函数,模板,默认参数或其他东西 - 如果你不使用宏,你会得到文件名&



使用宏。



编辑:



即使 C++常见问题表示宏有时是两种邪恶的较小者。



EDIT2:



正如Nathon在下面的评论中所说的,在使用宏的情况下,最好是明确的。给你的宏宏名称,如 COMMIT()而不是 Commit()。这将使维护者&调试器有一个宏调用,它应该有助于在大多数情况下避免冲突。两件好事。


I'm used to this:

class Db {
  _Commit(char *file, int line) {
    Log("Commit called from %s:%d", file, line);
  }
};

#define Commit() _Commit(__FILE__, __LINE__)

but the big problem is that I redefine the word Commit globally, and in a 400k lines application framework it's a problem. And I don't want to use a specific word like DbCommit: I dislike redundancies like db->DbCommit(), or to pass the values manually everywhere: db->Commit(__FILE__, __LINE__) is worst.

So, any advice?

解决方案

So, you're looking to do logging (or something) with file & line info, and you would rather not use macros, right?

At the end of the day, it simply can't be done in C++. No matter what mechanism you chose -- be that inline functions, templates, default parameters, or something else -- if you don't use a macro, you'll simply end up with the filename & linenumber of the logging function, rather than the call point.

Use macros. This is one place where they are really not replaceable.

EDIT:

Even the C++ FAQ says that macros are sometimes the lesser of two evils.

EDIT2:

As Nathon says in the comments below, in cases where you do use macros, it's best to be explicit about it. Give your macros macro-y names, like COMMIT() rather than Commit(). This will make it clear to maintainers & debuggers that there's a macro call going on, and it should help in most cases to avoid collisions. Both good things.

这篇关于将调用者__FILE__ __LINE__传递到函数而不使用宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆