yohhoyの日記

技術的メモをしていきたい日記

Visual Studio 2012でサポート済みのC++14機能

Microsoft Visual Studio 2012(MSVC11)でサポートされているC++14機能についてメモ。本記事の内容はMicrosoft Build 2013 "The Future of C++"スライド資料に基づく。

MSVC11では、C++14導入予定の「ラムダ式の戻り値型推論の制限緩和」に対応しているとのこと。下記コード例のようにreturn文が複数ある場合、C++11ラムダ式では戻り値型=voidに推論されるが*1C++14ラムダ式では同一型(some_typeと例示)へ推論される*2

p32: C++14 lambda return type deduction
Draft C++14 (approved in Bristol)
(Already supported in Visual Studio 2012)

[=] {                     // ok, deduced "-> some_type"
  while( something() ) {
    if( expr ) {
      return foo() * 42;  // with arbitrary control flow 
    }
    return bar.baz(84);   // & multiple returns
  }                       // (types must be the same)
}

C++14ラムダ式の戻り値型推論に失敗するコードで試すと、MSVC11コンパイラはエラーC3487を報告する。

auto lm = [] (bool b) {
  if (b) {
    return 42;   // int
  } else {
    return 'c';  // char
  }
};
// error C3487: 'char': ラムダ内のすべての return 式で同じ型が必要です。以前は 'int' でした

なお、C++14ラムダ式の「パラメータ(仮引数)へのauto指定」(多相ラムダ)には非対応。

[] (auto a) { }
// error C3533: 'auto': パラメーターは 'auto' を含む型にできません

関連URL

*1:C++11(N3337) 5.1.2/p4

*2:C++14 CD(N3690) 5.1.2/p4, 7.1.6.4/p9