C++におけるテンプレートの基本構文
メニューを表示するにはスワイプしてください
テンプレートの作成は実際には非常に簡単であり、テンプレートを使用する際の最も簡単な部分の一つです。まず、関数またはクラスのいずれかを作成する必要があります。ここでは関数から始めます。
main.cpp
123456void MyFirstTemplate() { } int main() { MyFirstTemplate(); }
ご覧の通り、現時点では何もしない非常にシンプルな関数があります。main関数内で簡単に呼び出すことができます。次の課題は、これをテンプレートに変換することです。
template.h
123456789101112// To create a template, you need to add code above the function or class // Start with the keyword `template` to indicate you're defining a template // template // Add angle brackets `<>`, this is list of the parameters for template // template < > // Inside of it has to be keyword `typename` and the name of it // template <typename Name> template <typename Name> void MyFirstTemplate() { }
次に、何かを実行してみましょう。たとえば、メッセージを出力します。main関数内で呼び出して、実際に動作する様子を確認してください。
main.cpp
123456789101112#include <iostream> template<typename Name> void MyFirstTemplate() { std::cout << "c<>definity" << std::endl; } int main() { MyFirstTemplate(); }
ご覧のとおり、エラーは、通常の関数のように呼び出そうとした場合に発生します。これは、もはや単なる関数ではないためです。この時点で、template キーワードの後の山括弧内に指定されたテンプレートパラメータが重要になります。
main.cpp
12345678910111213#include <iostream> // This essentioally creates an alias for a type you will use template<typename Name> // In this case the name of the type is Name void MyFirstTemplate() { std::cout << "c<>definity" << std::endl; } int main() { // In order to call the template function properly // You need to specify any type inside the brackets MyFirstTemplate<void>(); // This tells the template to use void as the type for Name }
注意
この例ではどの型を指定しても問題ありませんので、void を任意の型に変更できます。ただし、型の指定は必須です。
MyFirstTemplate 関数テンプレートでは、型パラメータに名前を指定する必要はありません。Name を削除しても、関数内で型パラメータが使用されていないため、問題なく動作します。
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 2
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 1. 章 2