using an absolute pointer address as a template argument

前端 未结 6 2541
攒了一身酷
攒了一身酷 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:34

    The declaration bar<(foo*)0x80103400> myFoo; is ill-formed because non-type template arguments must be a constant expression, from [temp.arg.nontype]:

    A template-argument for a non-type template-parameter shall be a converted constant expression (5.20) of the type of the template-parameter.

    And the argument you are passing is not, from [expr.const]:

    A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:
    — [...]
    — a reinterpret_cast (5.2.10);
    — [...]

    The declaration bar<(foo*)0> huh works since it does not involve a cast, it's simply a null pointer of type foo* (0 is special) and so it is a valid constant expression.


    You could instead simply pass in the address as a template non-type parameter:

    template 
    struct bar { ... };
    
    bar<0x8013400> myFooWorks;
    

    That is viable.

提交回复
热议问题