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>();
}
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>();
}
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
}
To be honest, I can't think of much a use for this type of construct, although I'm sure they probably exist. It seems to me that you're restricted because n must exist effectively at global scope for f() to be valid. You could do something like the following:
#include <iostream>
using namespace std;
template<int &n> void sq(){
n *= n;
}
int something = 10;
int main()
{
cout << something << endl;
sq<something>();
cout << something << endl;
return 0;
}
but I can't see what that's really going to give you that can't be achieved using non-template functions. Would sq()
effectively get calculated at compile time perhaps?