Have an amazing solution built in RAD Studio? Let us know. Looking for discounts? Visit our Special Offers page!
C++RAD Studio

C++Builderで戻り値の型推論(auto)の使用方法を学ぶ

learn-how-to-use-return-type-deduction-in-c

このブログでは、C++Builderで戻り値の推論の使用方法を学習します。

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型のサポートは、こちらを参照ください。また、戻り値の型推論を詳しく知りたい方は、公式ドキュメントを参考ください。

このブログで紹介しましたサンプルコードは、こちらからダウンロードできます。

C++Builder 10.4では、最新のC++17の言語仕様をサポートしており、C++17の新機能もすぐに試せます。製品の詳細は、こちらを参照してください。

「C++Builderで使用方法を学ぶ」シリーズのバックナンバー

RAD Studio 13.2 Florence Now Available! Kai 1.1.1 Now Available! What's Coming in RAD Studio 13.2 Florence

Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.

Start Free Trial   Upgrade Today

   Free Delphi Community Edition   Free C++Builder Community Edition

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

IN THE ARTICLES