2.6 KiB
2.6 KiB
nameof() c++11
C++ alternative to nameof operator in C#.
Linux/OSX | Windows |
---|---|
Used to obtain the simple name of a variable, type, member or function and etc. Before, you had to use string literals to refer to definitions, which is brittle when renaming code elements because tools do not know to check these string literals.
A nameof macros expression has this form:
std::cout << NAMEOF(person.address.zip_code) << std::endl; // prints "zip_code"
Features
- Simple name
- C++11
- Header-only
- Dependency-free
- Compile-time
- Compilation check
Example & Key Use Cases
- Name of a variable, member or function and etc
NAMEOF(someVar) -> "someVar"
NAMEOF(someVar.SomeField) -> "SomeField"
NAMEOF(someVar.SomeMethod1()) -> "SomeMethod1()"
NAMEOF(&SomeStruct::SomeMethod2) -> "SomeMethod2"
- Name of enum
NAMEOF(SomeEnum::RED) -> "RED"
NAMEOF(SomeEnum::GREEN) -> "GREEN"
- Name of type
NAMEOF_TYPE(int[]) -> "int[]"
NAMEOF_TYPE(std::string) -> "string"
- Constexpr
void f() {
int i;
constexpr auto constexpr_work_fine = NAMEOF(i); -> "i"
}
- Compilation check
void f() {
int i;
NAMEOF(i); -> "i"
NAMEOF(iii); -> error identifier "iii" is undefined
NAMEOF_TYPE(std::stringgg) -> error namespace "std" has no member "stringgg"
}
- Validate parameters
void f(char* s) {
if (s == nullptr)
throw std::invalid_argument(NAMEOF(s));
}
- Serialization, for example json:
void to_json(json& j, const person& p) {
j = json{{NAMEOF(p.name), p.name},
{NAMEOF(p.address), p.address},
{NAMEOF(p.age), p.age}};
}
void from_json(const json& j, person& p) {
p.name = j.at(NAMEOF(p.name));
p.address = j.at(NAMEOF(p.address));
p.age = j.at(NAMEOF(p.age));
}
- Logging
void f() {
Log(NAMEOF(f), " method entry");
}
Remarks
If you need to get the fully-qualified name, you can use the NAMEOF_FULL(). For example:
NAMEOF_FULL(someVar.SomeField) -> "someVar.SomeField"
NAMEOF_FULL(&SomeStruct::SomeMethod2) -> "&SomeStruct::SomeMethod2"
NAMEOF_TYPE_FULL(std::string) -> "std::string"