C++拾趣——编译器预处理宏__COUNTER__的应用场景

16 篇文章 9 订阅

在C++中,__COUNTER__是一个特殊的预处理宏,它主要被用来生成唯一的整数标识符。这个宏是由一些编译器(如GCC和Visual Studio)内置支持的,而不是C++标准的一部分。它的主要应用场景是在宏定义中,用于确保每次宏实例化时都能获得一个唯一的标识符,这在处理模板元编程、避免名称冲突或生成唯一标识符等场景中特别有用。

__COUNTER__宏每次被引用时,都会返回一个从0开始的连续递增的整数值。这意味着,在代码的不同部分或不同文件中使用__COUNTER__时,它都能保证生成唯一的整数。这对于在编译时生成唯一的变量名、函数名或枚举值等非常有帮助。

需要注意的是,因为__COUNTER__不是C++标准的一部分,所以它的具体行为可能因编译器而异。例如,某些编译器可能只在一个编译单元(translation unit)内保证__COUNTER__的唯一性,而另一些编译器则可能在整个程序中保证__COUNTER__的唯一性。

我们看下__COUNTER__的应用场景和事例:

生成唯一标识符

在需要唯一标识符的地方,__COUNTER__ 可以确保每次生成的值都是唯一的。

#include <iostream>
#include <thread>
#include <chrono>

// 定义宏,使用 __COUNTER__ 生成唯一的线程编号
#define THREAD_ID __COUNTER__

void threadFunction(int id) {
    while (true) {
        std::cout << "Thread [" << id << "] is running." << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

int main() {
    // 创建三个线程,每个线程都有唯一的编号
    std::thread t1(threadFunction, THREAD_ID);
    std::thread t2(threadFunction, THREAD_ID);
    std::thread t3(threadFunction, THREAD_ID);

    // 等待线程完成(在这个例子中,线程会一直运行)
    t1.join();
    t2.join();
    t3.join();

    return 0;
}

上面这段代码,创建3个线程时,我们希望每个线程有不同的ID。于是我们借助THREAD_ID的宏展开,让其值在编译期间确定为0~2,从而帮助我们避免手工设定0、1、2这样的数字。

需要注意的是,这段代码不能修改成For循环这类运行时生成线程的模式。因为__COUNTER__ 是在编译期间展开确定的,即编译器期间确定了它的值,在运行时时不改变的。
在这里插入图片描述

调试信息

在调试代码时,可以使用 __COUNTER__ 生成唯一的日志条目编号。这样会方便我们分析程序执行流程。

#include <iostream>
#include <string>

// 定义日志宏,使用 __COUNTER__ 生成唯一的日志条目编号
#define LOG_DEBUG(msg) \
    std::cout << "Log Entry [" << __COUNTER__ << "]: " << msg << std::endl;

void exampleFunction(int value) {
    LOG_DEBUG("Entering exampleFunction with value: " + std::to_string(value));

    if (value < 0) {
        LOG_DEBUG("Value is negative, returning early.");
        return;
    }

    LOG_DEBUG("Performing some operations...");
    // 模拟一些操作
    for (int i = 0; i < value; ++i) {
        LOG_DEBUG("Operation " + std::to_string(i));
    }

    LOG_DEBUG("Exiting exampleFunction.");
}

int main() {
    exampleFunction(3);
    exampleFunction(-1);
    exampleFunction(5);

    return 0;
}

在exampleFunction中,我们一共在5处打印了Log,其中有些Log是在分支中执行的,有些Log是在循环中执行的。我们可以通过添加了 __COUNTER__ 的日志快速确定代码的执行流程。
在这里插入图片描述
比如上图第1个流程中,就没有进入【1】这个分支;第2个流程,从【1】这个流程中直接退出了;第3个流程运行了所有“锚点”。

宏展开

在复杂的宏展开过程中,__COUNTER__可以确保生成的代码片段具有唯一性,避免命名冲突。

下面这个例子模拟《Robot Operating System——深度解析手动加载动态库的运行模式》中Node注册的流程。我们会通过静态变量自动初始化的特性,在其初始化过程中,自动注册若干继承于Base的子类对象。由于有多个子类需要注册,我们就需要多个静态变量。而我们希望有统一的方式来注册它们,这样就需要使用一种统一的方式生成不同的变量名。

我们先声明一个基类Base。它提供了一个纯虚方法display。

#ifndef BASE_H
#define BASE_H

class Base {
public:
    virtual ~Base() = default;
    virtual void display() const = 0;
};

#endif // BASE_H

然后提供一个工厂类用于注册对象。注意instance是个静态变量,这样不同地方调用Factory::instance()都会获得统一个对象,进而将不同的Base子类对象注册进来。

#ifndef FACTORY_H
#define FACTORY_H

#include <iostream>
#include <map>
#include <string>
#include <functional>
#include <memory> // for std::shared_ptr


#include "base.h"

class Factory {
public:
    using CreateFunc = std::function<std::shared_ptr<Base>()>;

    static Factory& instance() {
        static Factory instance;
        return instance;
    }

    void registerClass(const std::string& className, CreateFunc createFunc) {
        registry_[className] = std::move(createFunc);
    }

    std::shared_ptr<Base> create(const std::string& className) {
        auto it = registry_.find(className);
        if (it != registry_.end()) {
            return it->second();
        }
        return nullptr;
    }

private:
    std::map<std::string, CreateFunc> registry_;
};

#endif // FACTORY_H

继承于Base的子类只要实现display方法,然后通过REGISTER_CLASS来注册。

#ifndef DERIVED_A_H
#define DERIVED_A_H

#include <iostream>

#include "macro.h"
#include "base.h"

class DerivedA : public Base {
public:
    void display() const override {
        std::cout << "DerivedA instance" << std::endl;
    }
};


REGISTER_CLASS(DerivedA)

#endif // DERIVED_A_H

该宏的实现如下

#ifndef MACRO_H
#define MACRO_H

#include <memory>
#include <functional>
#include <string>

#include "factory.h"
#include "base.h"

#define REGISTER_CLASS(className) \
    REGISTER_CLASS_INTER(className, __COUNTER__)

#define REGISTER_CLASS_INTER(className, index) \
    REGISTER_CLASS_WITH_COUNTER(className, index)

#define REGISTER_CLASS_WITH_COUNTER(className, index) \
    class Factory##index { \
    public: \
        Factory##index() { \
            Factory::instance().registerClass(#className, []() -> std::shared_ptr<Base> { return std::make_shared<className>(); }); \
        } \
    }; \
    static Factory##index global_##index;

#endif // MACRO_H

它会自动生成静态变量global_0。这个变量的初始化时,会调用Factory0类的构造函数,从而将类的对象注册到Factory中。

如果此时我们再注册一个类

#ifndef DERIVED_B_H
#define DERIVED_B_H

#include <iostream>

#include "macro.h"
#include "base.h"

class DerivedB : public Base {
public:
    void display() const override {
        std::cout << "DerivedB instance" << std::endl;
    }
};

REGISTER_CLASS(DerivedB)

#endif // DERIVED_B_H

就会生成一个新的类Factory1和静态变量global_0。

然后我们就可以在Main函数中获取这些类的对象,然后加以使用

#include <memory> // for std::shared_ptr

#include "derived_a.h"
#include "derived_b.h"

int main() {
    Factory& factory = Factory::instance();

    std::shared_ptr<Base> a = factory.create("DerivedA");
    if (a) {
        a->display();
    } else {
        std::cout << "DerivedA not found" << std::endl;
    }

    std::shared_ptr<Base> b = factory.create("DerivedB");
    if (b) {
        b->display();
    } else {
        std::cout << "DerivedB not found" << std::endl;
    }

    return 0;
}

在这里插入图片描述

模板元编程

在 C++ 模板元编程中,__COUNTER__可以用于生成唯一的模板实例。

我们还是以注册类的为例,只是我们将宏中的类变成模板类。

#ifndef CLASS_FACTORY_H
#define CLASS_FACTORY_H

#include <string>
#include <memory>
#include <cxxabi.h> // for abi::__cxa_demangle

#include "factory.h"
#include "base.h"

template<class T, int N> 
class ClassFactory { 
public: 
    ClassFactory() { 
        Factory::instance().registerClass(getClassName(), []() -> std::shared_ptr<Base> { return std::make_shared<T>(); }); \
    } 
private:
    std::string getClassName() {
        const char* name = typeid(T).name();
        int status = 0;
        char* demangled = abi::__cxa_demangle(name, nullptr, nullptr, &status);
        std::string className = (status == 0) ? demangled : name;
        free(demangled);
        return className;
    }
}; 

#endif // CLASS_FACTORY_H

上例中比较少见的是abi::__cxa_demangle函数,它用于将编译器生成的类型名(mangled name)转换为人类可读的形式。然后我们将这个名字和指向子类的Base智能指针绑定。

这样我们的宏就会比较简单

#ifndef MACRO_H
#define MACRO_H

#include "class_factory.h"

#define REGISTER_CLASS(className) \
    REGISTER_CLASS_INTER(className, __COUNTER__)

#define REGISTER_CLASS_INTER(className, index) \
    DECLARE_GLOBAL(className, index)

#define DECLARE_GLOBAL(className, index) \
    static ClassFactory<className, index> global_##index;

#endif // MACRO_H

main函数和上例中一样,此处不表了。
在这里插入图片描述

代码

https://github.com/f304646673/cpulsplus/tree/master/counter

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

breaksoftware

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值