views:

54

answers:

2

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>();
}
+4  A: 

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
}
DeadMG
:). I should have been more careful with reading the error message
Chubsdad
A: 

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?

Robin Welch
For example, it could be used to implement a native C++ property, where the getter reads a variable and the setter writes that variable after calling some validation routine, then calls a change notification routine.
Ben Voigt
The non-template version would have to keep a pointer to the variable, in the template version that pointer will be optimized away and not need runtime storage.
Ben Voigt