Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 非型テンプレートパラメータ | テンプレートの使用
C++テンプレート
セクション 2.  3
single

single

book非型テンプレートパラメータ

メニューを表示するにはスワイプしてください

テンプレートを定義する際には、型だけでなく値も指定することが可能。これにより、与えられた値によって動作が異なるテンプレートを作成できる。ただし、この点については後ほど詳しく説明する。

main.cpp

main.cpp

copy
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

main.cpp

copy
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 変数の型を変更し、テンプレートパラメータとして渡せるようにする。

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  3
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt