फ़ंक्शन नाम आइडेंटिफायर्स
यहां हम __FUNCTION__, __func__ और __PRETTY_FUNCTION__ के बीच अंतर देखेंगे।
मूल रूप से __FUNCTION__ और __func__ समान हैं। C और C++ के कुछ पुराने संस्करण __func__ का समर्थन करते हैं। यह मैक्रो वर्तमान फ़ंक्शन का नाम प्राप्त करने के लिए उपयोग किया जाता है। __PRETTY_FUNCTION__ फ़ंक्शन के बारे में विवरण वापस करने के लिए उपयोग किया जाता है। इसका उपयोग करके हम प्राप्त कर सकते हैं कि कौन सा फ़ंक्शन उपयोग किया गया है, और यह किस क्लास से संबंधित है, आदि।
उदाहरण
#include <iostream>
using namespace std;
class MyClass {
public:
void Class_Function() {
cout << "The result of __PRETTY_FUNCTION__: " << __PRETTY_FUNCTION__ << endl;
}
};
void TestFunction() {
cout << "Output of __func__ is: " << __func__ << endl;
}
int main() {
cout << "Output of __FUNCTION__ is: " << __FUNCTION__ << endl;
TestFunction();
MyClass myObj;
myObj.Class_Function();
return 0;
}
आउटपुट (GCC/Clang)
Output of __FUNCTION__ is: main Output of __func__ is: TestFunction The result of __PRETTY_FUNCTION__: void MyClass::Class_Function()
तुलना तालिका
| आइडेंटिफायर | स्टैंडर्ड | कंटेंट | उदाहरण आउटपुट |
|---|---|---|---|
__func__ | C99, C++11 | केवल फ़ंक्शन नाम | "main" |
__FUNCTION__ | GCC/MSVC एक्सटेंशन | केवल फ़ंक्शन नाम | "main" |
__PRETTY_FUNCTION__ | GCC/Clang एक्सटेंशन | पूर्ण सिग्नेचर | "void MyClass::Class_Function()" |
__FUNCSIG__ | MSVC एक्सटेंशन | पूर्ण सिग्नेचर (MSVC स्टाइल) | "void __cdecl MyClass::Class_Function(void)" |
व्यावहारिक उपयोग
लॉगिंग मैक्रो
// पोर्टेबल बेसिक लॉगिंग
#define LOG(msg) std::cerr << "[" << __func__ << "] " << msg << '\n'
// GCC/Clang पर विस्तृत लॉगिंग
#if defined(__GNUC__) || defined(__clang__)
#define DETAILED_LOG(msg) std::cerr << "[" << __PRETTY_FUNCTION__ << "] " << msg << '\n'
#else
#define DETAILED_LOG(msg) LOG(msg)
#endif
void processData(int id) {
LOG("Processing started");
DETAILED_LOG("Processing with ID");
// ...
}
एरर मैसेजेस में
void validateInput(int value) {
if (value < 0) {
throw std::invalid_argument(
std::string(__func__) + ": value must be non-negative, got " +
std::to_string(value)
);
}
}
नोट्स
__func__एक वेरिएबल है (मैक्रो नहीं) -static const char __func__[] = "function-name";__PRETTY_FUNCTION__कंपाइलर-विशिष्ट है - पोर्टेबल कोड के लिए__func__पसंद करें- इनलाइन फ़ंक्शन्स और टेम्पलेट्स के साथ, आउटपुट कंपाइलर के बीच भिन्न हो सकता है
- C++20
std::source_locationएक स्टैंडर्ड विकल्प प्रदान करता है
C++20 std::source_location
#include <source_location>
#include <iostream>
void log(const std::string& msg,
const std::source_location& loc = std::source_location::current()) {
std::cerr << "[" << loc.function_name() << ":" << loc.line() << "] " << msg << '\n';
}
void foo() {
log("Hello from foo"); // स्वचालित रूप से foo और लाइन नंबर कैप्चर करता है
}