简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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