using an absolute pointer address as a template argument

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

    From the C++11 Standard (emphasis mine):

    14.3.2 Template non-type arguments

    1 A template-argument for a non-type, non-template template-parameter shall be one of:

    — for a non-type template-parameter of integral or enumeration type, a converted constant expression (5.19) of the type of the template-parameter; or

    — the name of a non-type template-parameter; or

    — a constant expression (5.19) that designates the address of an object with static storage duration and external or internal linkage or a function with external or internal linkage, including function templates and function template-ids but excluding non-static class members, expressed (ignoring parentheses) as & id-expression, except that the & may be omitted if the name refers to a function or array and shall be omitted if the corresponding template-parameter is a reference; or

    — a constant expression that evaluates to a null pointer value (4.10); or

    When compiled with g++ -Wall, I get the following error:

    error: ‘2148545536u’ is not a valid template argument for ‘foo*’ because it is not the address of a variable
        bar myFoo;        // fails with non-integral argument
                           ^ 
    

    It seems that the compiler is able to detect that 0x80103400 is not the address of a variable, it's just a constant expression.

提交回复
热议问题