using an absolute pointer address as a template argument

前端 未结 6 2450
攒了一身酷
攒了一身酷 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条回答
  •  Happy的楠姐
    2021-02-19 23:46

    Have you try casting the pointer address to and from uintptr_t, which is an unsigned integer capable of holding a pointer value? The type is defined in a standard header but it is only optional. If it does not exist in your version of C++, try size_t instead.

    A full example would then look like:

    #include 
    
    class foo
    {
        int baz;
    };
    
    template class bar
    {
        constexpr static const foo* f = (foo*)(addr);
    public:
        bar() {}
        void update() {  }
    };
    
    #define FOO_ADDR ((uintptr_t)0x80103400)
    
    int main() {
        bar myFoo;
    }
    

    The obvious drawback is that there is no typechecking at the template parameter. You pass a value which will hopefully refer to foo object and not a different one.

    Not to mention that we are in the undefined behavior world as far as the standard goes....


    You seem to be able to compile with the line

    constexpr static const foo* f = reinterpret_cast(addr);
    

    with at least some of the compilers as well (http://coliru.stacked-crooked.com/a/5af62bedecf2d75a)


    If your compiler rejects casting in the context of constexpr as it is ill-formed (as per Barry's comment) you can define it as a regular static const variable:

    template
    class bar
    {
        static const foo* f;
    public:
        bar() {}
        void update() {  }
    };
    
    template
    const foo* bar::f = reinterpret_cast(addr);
    

    Less ideal but solves that problem hopefully.

提交回复
热议问题