c++ - 关于C++预处理器的问题

标签 c++ c-preprocessor

我正在学习 C++ 宏。现在我完全糊涂了。所以帮帮我!下面是我的代码,我想做的是使用 C++ 宏并使用"template"调用不同的函数,这样我只能编写一个函数,并且该函数可用于为不同类型执行相同的操作。但是当我编译这段代码时,它会抛出以下错误。

testCPP.cpp: In function 'void test_int_Macro(int)':
testCPP.cpp:14: error: a function-definition is not allowed here before '{' token
testCPP.cpp:26: error: expected `}' at end of input**

#include<iostream>
#include<cstdint>

using namespace std;

#define Query_Data(Type)\
void test_##Type##_Macro(Type data){   \
    cout<<"Test: "<<sizeof(data)<<" "<<endl; \
    //cout<<"Type is "<<##Type##<<endl;\
}

Query_Data(int)
Query_Data(char)

int main(){
    cout<<sizeof(unsigned)<<endl;
    cout<<sizeof(char)<<endl;
    cout<<sizeof(int32_t)<<endl;
    int num=6;
    char c='a';
    Query_Data(num);
    //Query_Data(c);
}  

最佳答案

在 C++ 中,宏非常简单和愚蠢。 proeprocessor 只是简单地将宏定义的任何内容返回到您调用它的任何地方。

如果你在一张纸上做预处理,你得到的是:

int main(){
    cout<<sizeof(unsigned)<<endl;
    cout<<sizeof(char)<<endl;
    cout<<sizeof(int32_t)<<endl;
    int num=6;
    char c='a';
    void test_num_Macro(Type data){   
      cout<<"Test: "<<sizeof(data)<<" "<<endl; 
      //cout<<"Type is "<<##Type##<<endl;
    }
}  

编译器给了你一条错误信息,在这种情况下是正确的:

testCPP.cpp:14: error: a function-definition is not allowed here before '{' token

查看作为预处理结果的 main 函数。它有一个在其中声明的函数。显然,这是不允许的。

现在,如果我们按照这个思路进入下一个逻辑阶段,问题就变成了“那么我该如何实现我想要实现的目标?”

你说的是:

what I am trying to do is to use the C++ macro and call different functions using "template" such that I could only write one function and this function can be used to do the same things for different types.

C++ 中有一个工具可以做到这一点。巧合的是,它们被称为模板。以下是您可以在此处使用的方法:

template <typename Val>
void test ()
{
  cout << "Test: " << sizeof (Val) << " " << endl;
}

int main(){
    cout<<sizeof(unsigned)<<endl;
    cout<<sizeof(char)<<endl;
    cout<<sizeof(int32_t)<<endl;
    int num=6;
    char c='a';
    test <char> ();
    test <int> ();
}

宏是一个障碍。它们并不复杂,它们绕过 C++ 类型系统,很难调试和维护。通常建议避免使用它们,除非您别无选择。有些地方您确实别无选择——但这不是其中之一。

关于c++ - 关于C++预处理器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24831271/

相关文章:

c++ - 比较两个具有相同值的 TCHAR 结果为 false

c++ - 预处理器宏串联以构建类函数

c - 有没有一种方法可以同时检查宏是否已定义并且它等于某个值

C++ 构建器应用程序设置?

c++ - vector 消失

c++ - C++ 中的 Play again 选项不适用于数字猜谜游戏

c# - 为什么多语言解决方案不起作用?

c++ - 为什么预处理器宏是邪恶的,有哪些替代方案?

C 项目 - 如何管理功能列表?

c - 使用#define 定义结构对象