简体   繁体   English

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

[英]Can I ensure object created only once during compile time?

Avoid issues in run-time by asserting that object created once in compile time and avoid dynamic objects通过断言在编译时创建的对象并避免动态对象来避免运行时出现问题

Lets assume there are number of HW resources which can't be used by two modules of an app.让我们假设有许多硬件资源不能被应用程序的两个模块使用。 Let say Pins.比如说 Pins。 There are different hardware configurations and different builds are done - it would be great to make sure one HW resource (like a pin in simplest case) is used only once and not checking this in runtime.有不同的硬件配置和不同的构建完成 - 确保一个硬件资源(如最简单情况下的引脚)只使用一次而不在运行时检查它会很棒。

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

Then i can create然后我可以创建

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

I wonder if I can get compilation error/assert when I declare same pin one more time:我想知道当我再次声明相同的 pin 时是否会出现编译错误/断言:

Pin<2> pin2duplicate;

Yes, it is possible to guarantee that only a single instance is handling the data representation of a pin, also with multiple translation units for one application.是的,可以保证只有一个实例在处理 pin 的数据表示,也可以为一个应用程序提供多个翻译单元。

Idea: Make all data members of your template class static.想法:将模板类的所有数据成员设为静态。 As this, all the members are the same in all instances.因此,所有成员在所有情况下都是相同的 This should result in the expected behavior.这应该会导致预期的行为。 As every type ( and every template instance is a type ) has its own data, you can have multiple pins which each have each an own set of data.由于每种类型(并且每个模板实例都是一种类型)都有自己的数据,因此您可以有多个引脚,每个引脚都有自己的一组数据。

Example:例子:

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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM