预处理器 ## 粘贴运算符

Preprocessor ## pasting operator

本文关键字:运算符 处理器 预处理      更新时间:2023-10-16

我试图实现的是创建代码中提到的这三个类,但只是尝试方便地使用预处理器,以便可以创建和执行这些类似的类,而不是为它们编写单独的代码:

#include <iostream>
#define MYMACRO(len,baselen)
using namespace std;
class myclass ## len
{
    int MYVALUE ## baselen;
    public:
        myclass ## len ## ()
        {
            cout << endl;
            cout << " For class" ## len ## "'s function 'myFunction" ## len ## "' the value is: " << MYVALUE ## baselen << endl;
        }
};
int main()
{
    MYMACRO(10,100)
    //myclass10 ob1;
    MYMACRO(20,200)
    //myclass20 ob2;
    MYMACRO(30,300)
    //myclass30 ob3;
    myclass10 ob1;
    myclass20 ob2;
    myclass30 ob3;
    cout << endl;
    return 0;
}

现在我不知道是否可以完成,因为我收到此错误。如果是,那么请有人解决错误并启发我,如果没有,那么请给出相同的原因,这样我也放心,我们在同一页面上!错误是:

[root@localhost C++PractiseCode]# g++ -o structAndPreprocessor structAndPreprocessor.cpp
structAndPreprocessor.cpp:5: error: invalid token
structAndPreprocessor.cpp:6: error: invalid function declaration
structAndPreprocessor.cpp:7: error: invalid token
structAndPreprocessor.cpp:9: error: invalid token
structAndPreprocessor.cpp:9: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp:12: error: invalid token
structAndPreprocessor.cpp: In function `int main()':
structAndPreprocessor.cpp:25: error: `myclass10' was not declared in this scope
structAndPreprocessor.cpp:25: error: expected `;' before "ob1"
structAndPreprocessor.cpp:26: error: `myclass20' was not declared in this scope
structAndPreprocessor.cpp:26: error: expected `;' before "ob2"
structAndPreprocessor.cpp:27: error: `myclass30' was not declared in this scope
structAndPreprocessor.cpp:27: error: expected `;' before "ob3"
[root@localhost C++PractiseCode]#
您需要

在行的每一端使用 来定义宏(并可能从宏中删除 using 语句)

using namespace std;
#define MYMACRO(len,baselen) 
class myclass ## len 
{ 
    int MYVALUE ## baselen; 
(...snip...)       
   }
}; 

注意最后一行没有转义

很可能您正在执行 Cpp 并且不鼓励使用宏。您最好使用模板或传统的动态代码(根据您的需求)。与宏相比,模板在编译时引入了额外的类型检查,并提供更具可读性的错误消息。

您提出的宏解决方案是我以前使用过的解决方案,但我会以不同的方式看待这个问题。 宏解决方案是一个笨拙且难以维护和调试的所有代码,除了最琐碎的代码。

您是否考虑过从模板生成所需的代码? 使用 Cheetah 或 Mako 填写源模板会更简洁,您可以从配置文件驱动生成,因此您不必手动维护您的类列表。

你会有一个myclass.tmpl模板文件,看起来像这样:

#for len, baselen in enumerate(mylist_of_classes_i_want_to_generate)
class MyClass$len
{
    int MYVALUE$baselen;
    public:
        MyClass$len()
        {
            cout << endl;
            cout << " For class $len's function 'myFunction $len' the value is: " << MYVALUE$baselen << endl;
   }
};
#end for

然后,在编译之前,在生成流开始时调用 cheetah 自动生成代码。