[英]C++ compile-time class name string with validation
I would like a way to get a string from a class at compile time, but would also want an error if that class doesn't exist in the scope, so this is not enough:我想要一种在编译时从类中获取字符串的方法,但如果该类不存在于范围内,我也想要一个错误,所以这还不够:
#define CLASS_STR(c) # c
I guess I could write a post build script as a static analyzer of some sort.我想我可以编写一个构建后脚本作为某种静态分析器。
An example would be keypath checking in libextobjc http://devetc.org/code/2014/05/17/safe-and-sane-key-paths.html一个例子是 libextobjc http://devetc.org/code/2014/05/17/safe-and-sane-key-paths.html中的密钥路径检查
It should be simple to grasp, really.应该很容易掌握,真的。 Instead of writing "MyClass", one should utilize a macro that can return the class name in a string, while also making sure that class is visible in the scope.
与其编写“MyClass”,不如使用一个宏,该宏可以在字符串中返回类名,同时确保该类在作用域中可见。
Here is one way to do it:这是一种方法:
#include <iostream>
#include <MyLib/MyClass.h>
#define CLASS_STR(__class__) \
({ \
__class__ *x;\
#__class__ ;\
})
int main(int argc, char* argv[]) {
auto className = CLASS_STR(MyClass);
std::cout << className << std::endl;
return 0;
}
Notice if I passed in MyKlass
to the macro, it will fail to initialize the pointer, so now I have a compile time check that the class is available.请注意,如果我将
MyKlass
传递给宏,它将无法初始化指针,因此现在我有一个编译时检查该类是否可用。 After the check, I get a string, which is guaranteed to represent that class.检查后,我得到一个字符串,该字符串保证代表该类。
Of course, one can easily redefine the macro for release builds to just perform the stringification.当然,我们可以轻松地为发布版本重新定义宏以执行字符串化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.