Skip to content

Commit c32c334

Browse files
committed
Create __func__.cpp
1 parent d349091 commit c32c334

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

__func__.cpp

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*****************************************************************//**
2+
* \file __func__.cpp
3+
* \brief Demonstration of __cplusplus macro and __func__ signature
4+
* __func__ attribute of each function defaults to the name of such fn
5+
*
6+
* To compile on Windows:
7+
* $ g++ -o func.exe .\__func__.cpp -std=c++11
8+
* $ .\func.exe
9+
*
10+
* \author Xuhua Huang
11+
* \date October 2021
12+
*********************************************************************/
13+
14+
#if __cplusplus < 201103L
15+
#error "Should use C++ 11 implementation!"
16+
#endif
17+
18+
#include <iostream>
19+
#include <stdlib.h>
20+
#include <stdio.h>
21+
22+
#ifndef LOG
23+
#define LOG(...) {\
24+
fprintf(stderr, "%s: Line %d:\t", __FILE__, __LINE__);\
25+
fprintf(stderr, __VA_ARGS__);\
26+
fprintf(stderr, "\n");\
27+
}
28+
#endif // !LOG
29+
30+
#ifndef __USR_NO_EXCEPT__
31+
#define __USR_NO_EXCEPT__ true
32+
#endif
33+
34+
/* Function set to not throwing any exceptions
35+
* as per requested by the user using a macro.
36+
* std::terminate will handle all the panicking.
37+
*/
38+
const char* hello() noexcept(__USR_NO_EXCEPT__) {
39+
// Equivalence of defining the following manually:
40+
// static const char* __func__ = "hello";
41+
return __func__;
42+
}
43+
44+
const char* world() noexcept(__USR_NO_EXCEPT__) {
45+
// Equivalence of defining the following manually:
46+
// static const char* __func__ = "world";
47+
return __func__;
48+
}
49+
50+
/* __func__ in struct */
51+
typedef struct TestStruct {
52+
public:
53+
TestStruct() : name(__func__) {}
54+
const char* getName(void) { return name; }
55+
private:
56+
const char* name;
57+
} TestStruct;
58+
59+
int main(void)
60+
{
61+
/* Test __func__ predefined macro */
62+
std::cout << hello() << "\n"
63+
<<world() << std::endl;
64+
LOG("Function call hello() returns: %s", hello());
65+
LOG("Function call world() returns: %s", world());
66+
67+
/* Testing the LOG(...) macro */
68+
int x = 5;
69+
LOG("x = %d", x);
70+
71+
/* Testing TestStruct constructor with __func__ */
72+
TestStruct* ts = new TestStruct();
73+
LOG("__func__ in TestStruct constructor has the value of: %s", ts->getName());
74+
delete ts;
75+
76+
system("pause");
77+
return 0;
78+
}

0 commit comments

Comments
 (0)