我想通過宏或一些編譯器魔法獲得代碼中的完整函數路徑和聲明。我有這樣的代碼(click here to run):C++宏得到完整的函數路徑和聲明
#include <iostream>
namespace NS {
struct Foo {
static int sum(int a, int b) {
std::cout << "This is from " << __FILE__ << ":" << __LINE__ << " @ " << __func__ << std::endl;
return a+b;
}
static int sum(int a, int b, int c) {
std::cout << "This is from " << __FILE__ << ":" << __LINE__ << " @ " << __func__ << std::endl;
return a+b+c;
}
};
}
int main() {
NS::Foo::sum(1,2);
NS::Foo::sum(1,2, 3);
}
而我得到的輸出:
This is from /some/where/main.cpp:7 @ sum
This is from /some/where/main.cpp:12 @ sum
我的問題是:
- 我如何獲得
sum
功能的完整路徑調用? ?(NS::Foo::sum)
- 我怎樣才能得到完整的函數聲明與參數類型(
sum(int, int)
或sum(int, int, int)
)
我感興趣的主流編譯器:Clang, GCC, Microsoft C++ compiler
C不是C++不是C! – Olaf
@Olaf,感謝您的編輯。我明白,這只是一個壞習慣。 –
**前置處理器處理宏是有原因的。它們是文本替換,並且不瞭解「正常」C++代碼(btw。** this *與所有預處理器相同)。 – Olaf