セクション 1. 章 8
single
非型テンプレートパラメータ
メニューを表示するにはスワイプしてください
テンプレートを定義する際、型だけでなく値も指定できます。これにより、与えられた値によって動作が異なるテンプレートを作成できますが、この点については後ほど詳しく説明します。
main.cpp
123456789101112#include <iostream> // Non-type parameter means we won't use typename // Instead you can use an actual type for it template<int N> void PrintValue() { std::cout << N << std::endl; } int main() { // Call the template function with a literal integer PrintValue<5>(); // 5 }
この手法の主な利点は、すべての計算がコンパイル時に実行されるため、メタプログラミングで利用できる点です。
main.cpp
1234567891011#include <iostream> // Template function to calculate the square of a non-type parameter I template<int I> int Square() { return I * I; } // Return the square of I int main() { // The result of Square<5>() is computed at compile time int b = Square<5>(); // b will be initialized to 25 }
コンパイルされたプログラムを実行すると、b の値はすでに 25 になっています。計算はコンパイル時に行われるため、実行時の処理はゼロです。
タスク
スワイプしてコーディングを開始
テンプレート関数を完成させ、options および operations 変数の合計を求める。
- テンプレート関数を完成させる。
optionsおよびoperations変数の型を変更し、テンプレートパラメータとして渡せるようにする。
解答
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 8
single
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください