Search code examples
c++templatesparametersreferencenon-type

Non type template parameters of reference


What is the use of 'non type template' parameters which are of 'reference' type? Why are such parameters also treated as 'rvalues'?

template<int &n> void f(){
   &n;               // error
}

int main(){
   int x = 0;
   f<x>();
}

Solution

  • f<x> is invalid. My compiler compiles your templated function without the bad call just fine, by the way.

    template<int &n> void f(){
       int* ptr = &n;
    }
    
    int something = 0;
    
    int main() {
        f<something>(); // success
        int x;
        f<x>(); // C2971: Cannot pass local var to template function
    }