Kursinhalt
C++-Vorlagen
C++-Vorlagen
Implizite und Explizite Typspezifikation
Implizite Typspezifikation
In den meisten Fällen kann der C++-Compiler den Vorlagentyp automatisch aus den an die Funktion übergebenen Argumenten bestimmen. Wenn die Parametertypen alle benötigten Informationen liefern, ist es nicht notwendig, den Typ explizit anzugeben.
main
#include <iostream> template<typename T> void PrintValue(T value) { std::cout << value << std::endl; } // The compiler assigns the type for `T` // Based on the type of the passed argument `value` int main() { PrintValue(42); // `T` is deduced as `int` PrintValue(3.14); // `T` is deduced as `double` PrintValue("Hello"); // `T` is deduced as `const char*` }
Der Compiler bestimmt den Typ des Vorlagenparameters T
automatisch basierend auf den Funktionsargumenten. Dies macht die Funktionsaufrufe prägnanter und leichter lesbar. Aus diesem Grund haben Sie möglicherweise bereits Vorlagen verwendet, ohne es zu merken.
main
header
#include <iostream> int main() { int a = 300; int b = 200; // `std::swap` is actually a template and you can prove it // Try to specify `int` type explicitly `std::swap<int>` std::swap(a, b); std::cout << a << " " << b << std::endl; }
Explizite Typspezifikation
Bei all dem stellt sich die Frage: Wenn die Typableitung implizit ist, warum sollte man den Typ explizit angeben? Dies liegt daran, dass es Szenarien gibt, in denen die automatische Typableitung nicht funktioniert oder nicht ausreicht, sodass Sie den Vorlagentyp explizit angeben müssen. Schauen Sie sich einige Beispiele an.
ambiguous
forcing_type
no_parameters
#include <iostream> template<typename T> T GetDefaultValueSum(T a, T b) { return a + b; } int main() { // If `float` won't be specified, this code would generate an error std::cout << GetDefaultValueSum<float>(2, 2.5) << std::endl; }
Danke für Ihr Feedback!