LoginSignup
5
5

More than 5 years have passed since last update.

C++14: 関数からのreturn-typeを型推論する

Last updated at Posted at 2013-12-22

C++14では関数の戻り値の型を推論できます。

template<typename T, typename U>
auto add(const T& t, const U& u) { // -> decltype(t+u) は要らなくなった!
  return t + u;
}

int main() {
  cout << add(4, 10) << endl;
  cout << add(string("four"), "teen") << endl;
}

...ではコレは?

// コンテナの0番目を返す
template<typename C>
auto zeroth(C& c) {
  return c[0];
}

int main() {
  vector<int> vi = { 0, 1, 2, 3 };
  ++zeroth(vi); // [*] 0番目をインクリメントする
  cout << vi[0] << endl; 
}

残念。auto は cv-qualifier や 参照 を引っぺがし、この例では int と推論されるので(左辺値を) ++ できません。
が、decltypeは"そのまんま"の型となります:

vector<int> vi = { 0, 1, 2, 3 }
auto val = vi[0]; // int
decltype(vi[0]) ref = vi[0]; // int&

これを踏まえて、decltype(auto) が導入されます。やったね!

// コンテナの0番目を**参照で**返す
template<typename C>
decltype(auto) zeroth(C& c) {
  return c[0];
}

int main() {
  vector<int> vi = { 0, 1, 2, 3 };
  ++zeroth(vi); // [*] 0番目をインクリメントする
  cout << vi[0] << endl; 
}
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5