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 we will use template<typename Name> // In our 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 // We 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