using an absolute pointer address as a template argument

前端 未结 6 2561
攒了一身酷
攒了一身酷 2021-02-19 22:49

I have a template class which takes as its first template argument a foo * pointer. I\'d like to instantiate one of these with a foo located at an absolute address, like so:

6条回答
  •  爱一瞬间的悲伤
    2021-02-19 23:37

    Facing the same problem (on an STM32), as a work-around I found function pointer template parameters, like so:

    template
    class LedToggle
    {
        public:
    
        void Update()
        {
            // ...
            PORT()->BSRR = mSetReset & mask;
            // ...
        }
    };
    
    constexpr GPIO_TypeDef* Port_C() {
      return PORTC;
    }
    
    LedToggle led;
    

    Notice that we use a function pointer as template parameter, to a function that returns the desired actual pointer. Inside that function casts are allowed; and since the function is declared constexpr the compiler may (should) optimize away the actual function call and use the function's return value like a literal.

提交回复
热议问题