local variable as a non-typename argument

前端 未结 2 1940
名媛妹妹
名媛妹妹 2021-01-13 00:46

Why is it illegal to use a local variable as a non-type argument?

For example, in the next code local_var cannot be argument to X.

2条回答
  •  一生所求
    2021-01-13 01:28

    The "value" of a template needs to be present at compile time.

    template struct X {};
    

    Even if you do not bind a reference or pass a pointer here, the compiler must know the value of the passed elements at compile time.

    Replacing int &x with int x is on purpose here. Stuff about int& is answered correctly. I just wanted to point that it applies to all non-typed template arguments.

    • The "value" of a reference is a reference (implementation dependent actually a pointer in most of them)
      • The address of the object must be known at compile time
    • The "value" of a pointer template is an address...
      • ... which in turn must be known here, too, of course.
    • The "value" of a value-type is the value itself which also must be known at compile time

     

    X x; // will not work, local_var does not exist at compile time
    X<1> x; // works since 1 is known
    

    I just wanted to (in addition to Andy's answer) prevent any conclusions that would suggest to use a value type instead of a reference.

提交回复
热议问题