2

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;
user201202
  • 431
  • 1
  • 4
  • 7

1 Answers1

2

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.
}
Klaus
  • 24,205
  • 7
  • 58
  • 113
  • thanks for proposal. but this is not what i'm looking for. i want to be able to forbid creating p1duplicate. there is no issue with 'static' :) HW is "static" itself when comparing to program. Just want to avoid two object using same HW on compile/link stage – user201202 Jul 11 '19 at 13:31
  • @user201202: You misunderstood what is happening here: It makes no difference if a user creates p1duplicate or not. He can create as many duplicate's as he like, but they all are referring to the *same* instance of data. As this, the "system" is save to use, as having duplicates did not corrupt your software system anymore. It is like having multiple references to a single instance which you also can never avoid. As this all instances are referring to the same pin and the same data set and you can create as many instances without any problem anymore. – Klaus Jul 11 '19 at 14:34