开发者

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>();
}


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜