藍森林首頁 | 返回主頁 | 本站地圖 | 站內搜索 | 聯繫信箱 |
 您目前的位置:首頁 > 自由軟件 > 技術交流 > 應用編程


    

藍森林 http://www.lslnet.com 2006年6月6日 10:18


你的編譯器死了嗎?

#include <iostream>;
// primary template to compute sqrt(N)
template <int N, int LO=1, int HI=N>;
class Sqrt {
  public:
    // compute the midpoint, rounded up
    enum { mid = (LO+HI+1)/2 };

    // search a not too large value in a halved interval
    enum { result = (N<mid*mid) ? Sqrt<N,LO,mid-1>;::result
                                : Sqrt<N,mid,HI>;::result };
};

// partial specialization for the case when LO equals HI
template<int N, int M>;
class Sqrt<N,M,M>; {
  public:
    enum { result = M };
};

int main()
{
    std::cout << "Sqrt<23456>;::result = " << Sqrt<23456>;::result
              << '\n';
    std::cout << "Sqrt<25>;::result = " << Sqrt<25>;::result
              << '\n';
    std::cout << "Sqrt<42>;::result = " << Sqrt<42>;::result
              << '\n';
    std::cout << "Sqrt<1>;::result =  " << Sqrt<1>;::result
              << '\n';
}

如果你沒有發現編譯器死了, 那麼祝賀你! 你的機器很強勁! 以上代碼摘自《 C++ Templates - The Complete Guide》

你的編譯器死了嗎?

我的死了。
FreeBSD4.7, 內存128M。

你的編譯器死了嗎?

enum { result = (N<mid*mid) ? Sqrt<N,LO,mid-1>;::result
: Sqrt<N,mid,HI>;::result };
應該是這裡需要的運算過多

你的編譯器死了嗎?

這是對於模板技術的極致應用!

你的編譯器死了嗎?

過猶不及
設計程序時不一定要執意使用某個技術
而是看看它能不能更好的實現你的目標

你的編譯器死了嗎?

是啊我在調試這本書上面的示例的時候,也發現了這個問題。對於編譯效率和執行效率的權衡也是一個問題。

拋開這個示例的在便是實踐上的巨大的浪費,我還是覺得至少它演示了泛型技術的巨大生命力。值得我們去學習。

你的編譯器死了嗎?

想用泛型的話要有泛型設計的思維

這樣寫才可以寫得更好



Copyright © 1999-2000 LSLNET.COM. All rights reserved. 藍森林網站 版權所有。 E-mail : webmaster@lslnet.com