作者HuangTzHuan ()
看板C_and_CPP
标题Re: [语法] [问题] 关於pointer of reinterpret_cast
时间Wed Apr 1 02:19:24 2009
※ 引述《QQ29 (我爱阿蓉)》之铭言:
: ※ 引述《redluna (Occlumen)》之铭言:
: : 我们老师用了一个我看不懂得用法
: : template<typename T,int n> T sum(T (&a)[n]){
: : return a[0]+sum(reinterpret_cast<T(&)[n-1]>(a[1]));
: : ^^^^^^^^^^^^^^^^^^^^^^^^^^^
: : }
: : 我比较不懂的是这里
: : 是不是和template的展开有关
: : T(&) 是什麽意思?
: : 还是说要(&)(n)这样读?
: : 那和T*有甚麽不同?
: 你好:
: 我是因为研究了你这问题 才会发那些问题文章
: 我想T(&)[]就是如推文说的 cast成阵列的 reference
: 请参考这
: http://www.cnblogs.com/oomusou/archive/2007/02/09/646021.html
: 问题来了
: 你这个范例compile根本过不了
: 问题出在<T(&)[n-1]>
: rror C2265: 'abstract declarator' : 参考至大小为零的阵列不合法
: 改成<T(&)[n]>他就不会compile error了
: 在此想请问
: 为什麽compiler会去判断这件事呢?
: recursive不是runtime作的嘛 这边怎麽会跑出错误...
: 这是否可以解释成 这种template写法就是不能recursive?
: 不管我设什麽终止条件他都是在compile time给我错误讯息
: 请问有人知道为什麽嘛?
: 问题有点多 请各位多多指教 谢谢
改成这样可以 compile 也可以执行:
template<int n>
int sum(int (&a)[n])
{
return a[0]+sum(reinterpret_cast<int(&)[n-1]>(a[1]));
}
template<>
int sum<>(int (&a)[1])
{
return a[0];
}
考虑下面的 code:
int a[] = {1, 2, 3, 4};
int s = sum(a);
首先会呼叫 sum<4>(), 在 sum<4>() 里会呼叫 a[0] + sum<3>(a[1])
以此类推, 最後到 sum<1> 时由於我们提供了specialization 版本
所以递回到此终止, 答案也在 compile time 求得.
至於为什麽我要把 T 拿掉改用 int 呢?
因为 c++ 规定 function template 不能 partial specialization
因此我们没办法写
template<typename T>
T sum<T, 1>(T (&a)[1])
{
return a[0];
}
有人可能会想, 那我们就提供 function template overloading 呀
template<typename T>
T sum(T (&a)[1])
{
return a[0];
}
很遗憾的, 在 c++ 的 function overload resolution rules 之下
它还是会优先找到 template<typename, 1> T sum(T (&a)[1]) 这个版本
所以递回还是会缺乏终止条件
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.112.30.49
※ 编辑: HuangTzHuan 来自: 140.112.30.49 (04/01 02:29)
1F:推 QQ29:好深奥~~慢慢理解 04/01 02:50