您的位置:首页 > 其它

template<int N> struct A和template<const int N> struct A有区别吗?

2013-05-07 16:25 447 查看
个人认为如果你这么模版仅仅处理逻辑上是没任何区别的..

但是我以前碰到过这样的情况..下面我来说一下..

曾经我创建了一个模版 传入的是一个char*

运行一直很正常.有一天我突然发现程序会无缘无故崩溃..后来找出原因..因为我传入的一个字符串数据的地址发生了问题..后来发现我模版接收的数据为char*

可能是我在传入后做了其他的操作造成了他的地址发生了变化..或者是个临时变量等等问题..

后来改成了const char*后问题解决...

我觉得他们的区别在于首先是内存上的区别..

另外一个是防止被改变..或者数据丢失..

我觉得区别只是在于一个可以被修改一个不可修改.根据你需要的功能来定义才是主要的~

这种模板我知道有个用途,用于编译时递归的计算,比如求阶乘,通常用的是运行时的递归函数:

unsigned int factorial(unsigned int n) 

{

    if (n == 0)

       return 1;

    return n * factorial(n - 1);

}

 

void foo()

{

    int x = factorial(4); // == (4 * 3 * 2 * 1 * 1) == 24

    int y = factorial(0); // == 0! == 1

}


为了使用编译时的计算。

template <int N>

struct Factorial 

{

    enum { value = N * Factorial<N - 1>::value };

};

 

template <>

struct Factorial<0> 

{

    enum { value = 1 };

};

 

// Factorial<4>::value == 24

// Factorial<0>::value == 1

void foo()

{

    int x = Factorial<4>::value; // == 24

    int y = Factorial<0>::value; // == 1

}


如果把模板换成

template <const int N>

struct Factorial 

{

    enum { value = N * Factorial<N - 1>::value };

};


效果一样,但是如果两个模板一起定义,就出错了。说明是没有区别吧。?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐