在C++中,预处理器提供了一些符号和运算符,这些符号在宏定义中有特殊的含义

发布时间 2023-12-12 15:22:33作者: He_LiangLiang


在C++中,预处理器提供了一些符号和运算符,这些符号在宏定义中有特殊的含义。

以下是一些常见的符号:

#:字符串化运算符,用于将宏参数转换为字符串。

#define STRINGIZE(x) #x
std::cout << STRINGIZE(Hello); // 输出 "Hello"

##:连接运算符,用于连接两个标记,使它们成为一个标记。

#define CONCAT(a, b) a##b
int ab = CONCAT(3, 4); // 定义 int ab34;

__VA_ARGS__:可变参数宏的占位符,用于表示可变数量的参数。

#define LOG(format, ...) printf(format, __VA_ARGS__)
LOG("Hello %s!\n", "World"); // 输出 "Hello World!"

defined:用于检查宏是否已定义。

#ifndef MY_MACRO
#define MY_MACRO
#endif

#pragma:指令,用于向编译器发出特定的命令。

#pragma once

#ifdef#ifndef:条件编译指令,用于检查宏是否已定义。

#ifdef DEBUG
// 在调试模式下的代码
#endif

#elif#else:条件编译的分支指令,用于提供多个条件选择。

#ifdef DEBUG
// 调试模式下的代码
#else
// 非调试模式下的代码
#endif

#pragma message:生成编译时的消息。

#pragma message("This is a compile-time message")

#define#undef:定义和取消定义宏。

#define MY_MACRO
#undef MY_MACRO

#error:生成编译时错误消息。

#ifdef OLD_VERSION
#error "This version is no longer supported."
#endif

#pragma pack:用于设置结构体的对齐方式。

#pragma pack(push, 1)
struct MyStruct {
    char a;
    int b;
};
#pragma pack(pop)

__FILE____LINE__:分别表示当前源文件和当前行数。

#define LOG_ERROR(message) \
    std::cerr << "Error in file " << __FILE__ << " at line " << __LINE__ << ": " << message << std::endl;

 

 

一个宏定义的示例:

// test1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <functional>
#include <map>
#include <string>

// A simple FormatItem class for demonstration purposes
class SimpleFormatItem {
public:
    using ptr = std::shared_ptr<SimpleFormatItem>;

    SimpleFormatItem(const std::string& format) : format_(format) {}

    void print() const {
        std::cout << "Formatted output: " << format_ << std::endl;
    }

private:
    std::string format_;
};

// Define a map similar to the provided example
static std::map<std::string, std::function<SimpleFormatItem::ptr(const std::string& str)>> s_simple_format_items = {
#define SIMPLE_FORMAT(str, C) \
        {#str, [](const std::string& fmt) { return SimpleFormatItem::ptr(new C(fmt));}}

    SIMPLE_FORMAT(a, SimpleFormatItem),
    SIMPLE_FORMAT(b, SimpleFormatItem),
    SIMPLE_FORMAT(c, SimpleFormatItem),
#undef SIMPLE_FORMAT
};

int main() {
    // Example usage
    auto itemA = s_simple_format_items["a"]("Sample A");
    itemA->print();

    auto itemB = s_simple_format_items["b"]("Sample B");
    itemB->print();

    return 0;
}