我可以确保在编译时只创建一次对象吗?



通过断言在编译时创建一次的对象来避免运行时出现问题,并避免动态对象

假设有许多硬件资源不能被应用的两个模块使用。让我们说别针。有不同的硬件配置和不同的构建 - 确保一个硬件资源(如最简单的引脚(只使用一次而不在运行时检查它会很棒。

template <uint8_t pin> 
struct Pin {
    static constexpr uint8_t Number = pin;
    /*.... */
}

然后我可以创建

Pin<1> pin1;
Pin<2> pin2;

我想知道当我再次声明相同的引脚时,我是否会得到编译错误/断言:

Pin<2> pin2duplicate;

是的,可以保证只有一个实例处理引脚的数据表示,也可以为一个应用程序提供多个转换单元。

想法:将模板类的所有数据成员设置为静态。因此,所有成员在所有实例中都是相同的。这应该会导致预期的行为。由于每个类型(每个模板实例都是一个类型(都有自己的数据,因此您可以有多个引脚,每个引脚都有自己的一组数据。

例:

template <uint8_t pin>
struct Pin
{
    static constexpr uint8_t Number = pin;
    static bool state;
    void SetState( bool newState ) { state = newState; }
    bool CheckState() const { return state; }
};
template< uint8_t pin >
bool Pin<pin>::state = false;
int main()
{   
    Pin<1> p1; 
    Pin<1> p1duplicate;
    Pin<2> p2;
    std::cout << p1.CheckState() << std::endl;
    std::cout << p1duplicate.CheckState() << std::endl;
    std::cout << p2.CheckState() << std::endl;
    p1.SetState(true);
    std::cout << p1.CheckState() << std::endl;
    std::cout << p1duplicate.CheckState() << std::endl; // here we have the data also changed in the duplicate
    std::cout << p2.CheckState() << std::endl;   // as you can see, p2 is not changed as required.
}

最新更新