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

single

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

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

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

main.cpp

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

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 になっています。計算はコンパイル時に行われるため、実行時の処理はゼロです。

question mark

C++ テンプレートにおいて非型テンプレートパラメータを使用する主な利点は何ですか?

正しい答えを選んでください

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

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

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

セクション 2.  3
single

single

AIに質問する

expand

AIに質問する

ChatGPT

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

some-alt