C++Builderで戻り値の型推論(auto)を使用する
概要
C++14以降のバージョンでは、関数の戻り値の型にautoもしくはdecltype(auto)を記述しておくだけで、コンパイラは関数がどれほど複雑であっても、戻り値の型をreturn文から推論できます。
ただし推察できる条件を満たすには、return文が同じ型を持つ必要があり、実行方法はauto変数の場合と同じです。
実際のコード例を見てみましょう。
#ifdef _WIN32
#include <tchar.h>
#else
typedef char _TCHAR;
#define _tmain main
#endif
#include <string>
#include <memory>
#include <iostream>
// 関数aは、戻り値はint型を返す関数として推論される
auto a(){ return 1; };
// 関数bは、戻り値はdouble型を返す関数として推論される
auto b(){ return 1.2; };
// return文の型が一致しないため、コンパイルエラーになる
auto c()
{
return 1;
return 1.0;
};
int _tmain(int argc, _TCHAR* argv[]) {
// 戻り値は、int型として推論される
auto ret_a = a();
std::cout << "ret_a = " << ret_a << std::endl;
// 戻り値は、double型として推論される
auto ret_b = b();
std::cout << "ret_b = " << ret_b << std::endl;
system("pause");
return 0;
}
上記のコード例のように型を推論するためには、コンパイラは関数の定義を直前に検出する必要があります。つまり、この手法は、関数テンプレート、インライン関数、特定のtranslation unit内でのみ適用されるヘルパー関数に限定されます。
もう少し高度なコード例を見てみましょう。
#ifdef _WIN32
#include <tchar.h>
#else
typedef char _TCHAR;
#define _tmain main
#endif
#include <string>
#include <memory>
class employee {
// Lots of code here
};
struct person_id {
std::string first_name;
std::string last_name;
};
class employees {
public:
auto find_employee(const std::string& name) { return 1; }
};
int return_an_int() {
return 1;
}
auto return_something() {
return 1;
}
// The following will give a compiler error, because int and
// float are different types
//auto returnConfusion() {
// if (std::rand() %2 == 0) {
// return -1;
// } else {
// return 3.14159;
// }
//}
int main() {
auto i{ return_an_int() };
auto j{ return_something() };
// Example of a method with multiple return points, each with different types - an error
// auto k {returnConfusion()};
auto employee_list{ std::make_unique() };
auto person = employee_list->find_employee("Jane Smith");
system("pause");
return 0;
}
C++Builderのauto型のサポートは、こちらを参照ください。また、戻り値の型推論を詳しく知りたい方は、公式ドキュメントを参考ください。
この記事で紹介しましたサンプルコードは、こちらからダウンロードできます。
関連情報