Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Impliciete en Expliciete Typespecificatie | Templates Usage
C++-Templates

Impliciete en Expliciete Typespecificatie

Veeg om het menu te tonen

Impliciete typespecificatie

In de meeste gevallen kan de C++-compiler automatisch het sjabloontype bepalen op basis van de argumenten die aan de functie worden doorgegeven. Als de parameter­typen alle benodigde informatie bevatten, is het niet nodig om het type expliciet op te geven.

main.cpp

main.cpp

12345678910111213
#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*` }

De compiler bepaalt automatisch het type van de sjabloonparameter T op basis van de functieargumenten. Dit maakt de aanroepen van functies beknopter en beter leesbaar. Om deze reden heb je mogelijk al sjablonen gebruikt zonder dat je het doorhad.

main.cpp

main.cpp

header.h

header.h

123456789101112
#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; }

Expliciete typespecificatie

Hierbij rijst de vraag: als type-afleiding impliciet is, waarom zou je het type dan expliciet opgeven? Dit komt doordat er situaties zijn waarin automatische type-afleiding niet werkt of niet voldoende is, waardoor je het sjabloontype expliciet moet opgeven. Bekijk de volgende voorbeelden.

ambiguous.cpp

ambiguous.cpp

forcing_type.cpp

forcing_type.cpp

no_parameters.cpp

no_parameters.cpp

12345678910
#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; }
question mark

Wat is de verkeerde optie om de placeholder ___ in de volgende code te vervangen?

Selecteer het correcte antwoord

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 2. Hoofdstuk 2

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 2. Hoofdstuk 2
some-alt