如何在 C++ 中将模板类 ptr 转换为普通类 ptr
我对宏有疑问。我如何通过宏将模板类转换为普通类。例如:
#define RUNTIME_CLASS(class_name) ((CRuntimeClass*)(&class##class_name))
template<typename T> A {};
if (RUNTIME_CLASS(A));
我知道这段代码无法编译,因为它看不到模板位。但我不明白实际的宏。它的返回看起来像 (CRuntimeClass*)(&classA)
为什么 ##
连接使得 class + A ?预处理器如何理解这种表示法?
I have question regarding macros. How could I cast through macro a template class to normal class. In example:
#define RUNTIME_CLASS(class_name) ((CRuntimeClass*)(&class##class_name))
template<typename T> A {};
if (RUNTIME_CLASS(A));
I know that this code wouldn't compile because it will not see template bit. But I don't understand the actual macro. the return of it looks like (CRuntimeClass*)(&classA)
Why ##
concatenate makes class + A ? and how preprocessor understands such notation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许在您使用宏的地方,所有类名称都以“class”开头,而宏只需要名称的第二部分,即“class”之后的部分。
Maybe where you took the macro all the class names are starting with "class" and the macro expects only the second part of the name, what comes after "class".
我不明白这个问题。
首先 - 我不明白为什么你想将模板类转换为普通类。将模板类转换为具体类的方法是提供模板参数。如果没有这些参数,模板类尚未完全定义,因此根本无法使用。
在某种程度上,模板是一个在编译时评估以定义类/函数的函数。如果没有参数,尝试将模板视为类就像尝试将未评估的函数视为数字一样。
正如已经提到的,“##”是一个标记连接预处理器运算符。如果你没有想到这一点,我不明白你为什么要写“##”。
这与名称修改有关吗?
I don't understand the question.
First - I don't understand why you'd want to cast a template class into a normal class. The way to convert a template class into a concrete class is to supply the template parameters. Without those parameters, the template class has not been fully defined, and therefore simply cannot be used.
In a way, a template is a function that is evaluated at compile time in order to define a class/function. Without the parameters, trying to treat the template as a class is like trying to treat an unevaluated function as a number.
As already mentioned, "##" is a token concatenating preprocessor operator. If you aren't expecting that, I don't understand why you are writing "##".
Is this something to do with name mangling?
这就是它的作用,## 连接一个字符串和一个传递到 #define 的参数。
That's just what it does, ## concatenates a string and a parameter passed into your #define.