C++0x 去年就開始研究了,這東西是越看越頭痛,學(xué)到了幾個呼聲很高的簡化編碼的改進(jìn)。
auto:
C++中迭代器最讓人詬病的 就是那冗長繁瑣的聲明。像這樣: std::vector<int>::iterator iter= v.begin(); 我們的主要目的是聲明iter=v.begin(),但是卻要寫常常的一串std::vector<int>::iterator 篇幅比主角要多好多。這還算比較簡單的聲明,如果是boost里面的庫,有些類型聲明基本不是人能寫出來的。于是,為了響應(yīng)廣大群眾的呼聲,新標(biāo)準(zhǔn)改進(jìn)了auto關(guān)鍵字,現(xiàn)在可以這樣寫
auto iter=v.begin(); 具體的類型聲明交給編譯器去推斷了,這本來就是它最擅長的地方。
Variadic templates
模板技術(shù)的出現(xiàn)帶來了范型程序設(shè)計的發(fā)展,但是模板原本的一些限制,制約了很多美好的夢想??纯碽oost里面的tuple和functional,雖然有簡單方便的使用接口,內(nèi)部的實現(xiàn)卻晦澀難懂,以至于使用時,如果編譯器爆出了錯誤,其信息往往讓人云里霧里,不知所云。為了解決這些問題制約,新標(biāo)準(zhǔn)提出了不少語法新特性,Variadic templates 可變模板類型參數(shù)就是很 有意義的一項新特性。
現(xiàn)在一行代碼就可以搞定原先 要用宏,元編程等傷腦筋的技術(shù)才能解決的“小問題”。
#include <iostream>
#include <string>
#include <tr1/memory>
#include <boost/typeof/typeof.hpp>
template<typename T>
std::tr1::shared_ptr<T> New(){
return std::tr1::shared_ptr<T>(new T());
}
template<typename T,typename
Args>
std::tr1::shared_ptr<T> New(Args
args){
return std::tr1::shared_ptr<T>(new T(args
));
}
int main(){
BOOST_AUTO(p1,New<int>());
BOOST_AUTO(p2,New<int>(1));
BOOST_AUTO(p3,New<std::string>("hello world"));
std::cout<<*p1<<std::endl;
std::cout<<*p2+*p2<<std::endl;
std::cout<<p3->c_str()<<std::endl;
}
上面的代碼 解決了小問題 了卻了大麻煩#include <string>
#include <tr1/memory>
#include <boost/typeof/typeof.hpp>
template<typename T>
std::tr1::shared_ptr<T> New(){
return std::tr1::shared_ptr<T>(new T());
}
template<typename T,typename

std::tr1::shared_ptr<T> New(Args

return std::tr1::shared_ptr<T>(new T(args

}
int main(){
BOOST_AUTO(p1,New<int>());
BOOST_AUTO(p2,New<int>(1));
BOOST_AUTO(p3,New<std::string>("hello world"));
std::cout<<*p1<<std::endl;
std::cout<<*p2+*p2<<std::endl;
std::cout<<p3->c_str()<<std::endl;
}