template<int N> struct A和template<const int N> struct A有区别吗?
2013-05-07 16:25
447 查看
个人认为如果你这么模版仅仅处理逻辑上是没任何区别的..
但是我以前碰到过这样的情况..下面我来说一下..
曾经我创建了一个模版 传入的是一个char*
运行一直很正常.有一天我突然发现程序会无缘无故崩溃..后来找出原因..因为我传入的一个字符串数据的地址发生了问题..后来发现我模版接收的数据为char*
可能是我在传入后做了其他的操作造成了他的地址发生了变化..或者是个临时变量等等问题..
后来改成了const char*后问题解决...
我觉得他们的区别在于首先是内存上的区别..
另外一个是防止被改变..或者数据丢失..
我觉得区别只是在于一个可以被修改一个不可修改.根据你需要的功能来定义才是主要的~
这种模板我知道有个用途,用于编译时递归的计算,比如求阶乘,通常用的是运行时的递归函数:
为了使用编译时的计算。
如果把模板换成
效果一样,但是如果两个模板一起定义,就出错了。说明是没有区别吧。?
但是我以前碰到过这样的情况..下面我来说一下..
曾经我创建了一个模版 传入的是一个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 }; };
效果一样,但是如果两个模板一起定义,就出错了。说明是没有区别吧。?
相关文章推荐
- std::vector<std::string>::size_type和 int的区别
- vector<int>::iterator和vector<int*>::iterator还有vector<int>*的区别
- string和char*的区别以及const_cast<>()
- const vector <int> ::iterator和vector <int>::const_iterator有什么不同
- template <class T> T * funcNew(T x,int n)
- Error: undefined reference to `templatename<int,int >' ( error LNK2019: 无法解析的外部符号......)
- LNK2019: 无法解析的外部符号 "public: void __thiscall List<int>::add(int const &)" (?add@?$List@H@@QAEXABH@Z),
- 不能将参数 1 从“int”转换为“std::_Vector_const_iterator<_Myvec>”(VS2010 )
- &lt;%!int n = 1 %&gt; 与&lt;%int n = 1 %&gt; 的区别
- c++ 中 const_iterator 和 const vector<>::iterator的区别
- c++中vector<int>和vector<int*>的用法区别
- C++ error C2662: “LinkNode<T> *List<T>::Locate(int)”: 不能将“this”指针从“const List<int>”转换为“List<int> &”
- string和char*的区别以及const_cast<>()
- 用vector<int>对象元素,实现输入10数,将每个奇数值元素用该值的两倍替换
- "<br />"和 "\r\n" 这两者有什么区别??
- #include<stm32f10x_lib.h>和#include<stm32f10x.h>的区别
- asp.net <%%> <%#%><%=%><%@%><%$%>用法区别
- Java 运算符 &与&& << >> >>>区别
- Spring 开启Annotation <context:annotation-config> 和 <context:component-scan>诠释及区别
- C++:vector<vector<int> > a, int b[M][L].两种方式,那种效率高。 注:都采用下标寻址方式。