C++0xã®autoã®ç´¹ä»
autoãã¼ã¯ã¼ãã使ã£ã¦å¤æ°ãå®ç¾©ããã¨ï¼ã³ã³ãã¤ã©ãåæåå¤ãåºã«å¤æ°ã®åãæ¨è«ãã¦ãããï¼
int f(); auto x1 = 1; // x1 : int auto x2 = f(); // x2 : int auto x3 = 3.14; // x3 : double auto &x4 = x1; // x4 : int& const auto *x5 = &x1; // x5 : const int*
ã¤ãã¬ã¼ã¿ã®ããã«é·ãååã®åãautoã使ãã°ç°¡åã«æ¸ããï¼
// before for (std::vector<int>iterator it = v.begin(), end = v.end(); it != end; ++it) { ... } // after for (auto it = v.begin(), end = v.end(); it != end; ++it) { ... }
以ä¸ã®ãããªè¤éãªã¢ã¬ããããªé¢¨ã«ç°¡åã«ã¢ã¬ã§ããï¼
// before template<class Iterator> void f(Iterator it) { typename std::iterator_traits<Iterator>::value_type temp = *it; ... } // after template<class Iterator> void f(Iterator it) { auto temp = *it; ... }
ã©ã ãé¢æ°ãç°¡åã«ä»£å ¥ã§ããï¼
auto f = [](int n){ std::cout << n << std::endl; }; std::vector<int> v = {1, 2, 3, 4, 5}; // C++0xã®åæåãªã¹ã std::for_each(v.begin(), v.end(), f);
autoã使ããªãã±ã¼ã¹
autoã§å¤æ°ãå®ç¾©ããæã¯å¿ ãåæåãå¿ è¦ï¼
auto a; // NGï¼åæåãããªãã¨åãç¹å®ã§ããªãï¼
é¢æ°ã®å¼æ°ãæ»ãå¤ã®åã¯autoã«ã¯ã§ããªãï¼ãã®å ´åã¯ãã³ãã¬ã¼ãã使ããï¼
void f(auto x); // NGï¼å¼æ°ã®åã¯autoã«ã§ããªã auto g(); // NGï¼æ»ãå¤ã®åã¯autoã«ã§ããªã
autoã¨ãã¤ã³ã¿ã¨åç §
ãã¤ã³ã¿ãåç §ã絡ãã§ããæã®åæ¨è«ã«ã¤ãã¦ã¾ã¨ãã¦ã¿ãï¼
ã¾ãã¯ãã¤ã³ã¿ï¼autoã«ãã£ã¦æ¨è«ãããåããã¤ã³ã¿ã¨ãªãå ´åã¯ï¼autoã®æ¨ªã«æ示çã«ã*ããè¨è¿°ããå ´åï¼ã¾ãã¯åæåå¤ã®åããã¤ã³ã¿ã®å ´åï¼
A a; auto x1 = a; // x1 : A auto x2 = &a; // x2 : A* auto *x3 = &a; // x3 : A* auto *x4 = a; // ã¨ã©ã¼ï¼åæåå¤ããã¤ã³ã¿åã§ã¯ãªã A f(); auto y1 = f(); // y1 : A auto *y2 = f(); // ã¨ã©ã¼ï¼åæåå¤ããã¤ã³ã¿åã§ã¯ãªã A* g(); auto z1 = g(); // z1 : A* auto *z2 = g(); // z2 : A*
次ã¯åç §ï¼autoã«ãã£ã¦æ¨è«ãããåãåç §ã¨ãªãå ´åã¯ï¼autoã®æ¨ªã«æ示çã«ã&ããè¨è¿°ããå ´åã®ã¿ï¼
A a; auto x1 = a; // x1 : A auto &x2 = a; // x2 : A& A f(); auto y1 = f(); // y1 : A auto &y2 = f(); // ã¨ã©ã¼ï¼å³è¾ºå¤(ä¸æãªãã¸ã§ã¯ã)ã«å¯¾ãã¦å·¦è¾ºå¤åç §å¤æ°ãå®ç¾©ãããã¨ã¯ã§ããªã A& g(); auto z1 = g(); // z1 : A auto &z2 = g(); // z2 : A&
autoã¨åºåºã¯ã©ã¹ã®ãã¤ã³ã¿ã§çºçããåé¡
åºåºã¯ã©ã¹ã®ãã¤ã³ã¿çµç±ã§æ´¾çã¯ã©ã¹ã®ãªãã¸ã§ã¯ããåç §ãï¼ãããç¨ãã¦autoã§å®ç¾©ããå¤æ°ãåæåãããã¨ããã¨åé¡ãçºçãããã¨ãããï¼
class B { public: virtual ~B(){} }; class D : public B {}; D *pd = new D(); auto x1 = pd; // x1 : D* auto x2 = *pd; // x2 : D B *pb = new D(); auto y1 = pb; // y1 : B* auto y2 = *pb; // y2 : B (DããBã¸ã®ã¹ã©ã¤ã·ã³ã°ãçºçãã¦ããï¼)
ä¸ã®ã³ã¼ããg++ 4.6ã§å®è¡ããã¨ï¼pbã¯Dåã®ãªãã¸ã§ã¯ããæãã¦ããã«ããããããï¼y2ã¯Båã®ãªãã¸ã§ã¯ãã¨ãªã(typeid(y2) == typeid(B)ãçã«ãªã)ï¼ããããDåã®ãªãã¸ã§ã¯ãã§ãã*pbã®ãã¡Båã¨å ±éããé¨åã®ã¿ãy2ã«ä¸éå端ã«ã³ãã¼ããï¼Dåã®é¨åã®ã¡ã¢ãªã¯ã³ãã¼ãããï¼y2ã¯ä¸å®å ¨ãªãªãã¸ã§ã¯ãã¨ãªã£ã¦ãã¾ã£ã¦ããã®ã ããã¨èããããï¼autoã«ããåæ¨è«ã¯(ã³ã³ãã¤ã«æã«æ±ºå®å¯è½ãª)éçãªåã«ãã£ã¦è¡ããï¼ãã¤ã³ã¿ã®æãã¦ããå ã®ãªãã¸ã§ã¯ãã®åã¾ã§ã¯èæ ®ãããªãã¿ãããªã®ã§æ³¨æãå¿ è¦ã ï¼