Espaces de noms
Variantes
Affichages
Actions

Class template

De cppreference.com
< cpp‎ | language

 
 
Langage C++
Sujets généraux
Contrôle de flux
Instructions conditionnelles
Instructions d'itération
Instructions de saut
Fonctions
déclaration de fonction
expression lambda
fonction générique
spécificateur inline
spécification d'exception (obsolète)
spécificateur noexcept (C++11)
Exceptions
Espaces de noms
Types
spécificateur decltype (C++11)
Qualificatifs
qualificatifs const et volatile
qualificatifs de stockage
qualificatif constexpr (C++11)
qualificatif auto (C++11)
qualificatif alignas (C++11)
Initialisation
Littéraux
Expressions
opérateurs alternatifs
Utilitaires
Types
déclaration typedef
déclaration d'alias de type (C++11)
attributs (C++11)
Jette
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversions implicites
conversion const_cast
conversion static_cast
conversion dynamic_cast
conversion reinterpret_cast
conversions style C et style fonction
Allocation de mémoire
Classes
Qualificatifs spécifiques aux membres de classe
Fonctions membres spéciales
Modèles
classes génériques
fonctions génériques
spécialisation de modèles
paquets de paramètres (C++11)
Divers
Assembleur
 
Un modèle de classe définit une famille de classes .
Original:
A class template defines a family of classes.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Sommaire

[modifier] Syntaxe

template < parameter-list > declaration

[modifier] Explication

declaration définit ou déclare une classe (y compris struct et union), un membre de classe ou de type d'énumération membre, un fonction ou fonction membre, une donnée membre statique d'un modèle de classe, ou un alias de type. Il peut également définir une spécialisation de template. Cette page est consacrée modèles de classe .
Original:
declaration defines or declares a class (including struct and union), a member class or member enumeration type, a fonction ou fonction membre, a static data member of a class template, or a alias de type. It may also define a spécialisation de template. This page focuses on class templates.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
parameter-list est un non-vide séparées par des virgules liste des paramètres de modèle, dont chacun représente l'un des paramètres non-type, un type de paramètre, un paramètre de modèle, ou une Paquet de paramètre selon l'une quelconque de celles-ci. Cette page porte sur les paramètres qui ne sont pas les packs de paramètres .
Original:
parameter-list is a non-empty comma-separated list of the template parameters, each of which is either non-type parameter, a type parameter, a template parameter, or a Paquet de paramètre of any of those. This page focuses on the parameters that are not parameter packs.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[modifier] Paramètre de modèle non type

type name (1)
type name = default (2)
type ... name (3) (depuis C++11)
1)
Un paramètre de modèle non-type avec un nom facultatif
Original:
A non-type template parameter with an optional name
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
Un paramètre de modèle non-type avec un nom d'option et une valeur par défaut
Original:
A non-type template parameter with an optional name and a default value
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3)
Un modèle non-Paquet de paramètre type avec un nom facultatif
Original:
A non-type template Paquet de paramètre with an optional name
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
type est l'un des types suivants (éventuellement cv-qualifié, les qualificatifs sont ignorées)
Original:
type is one of the following types (optionally cv-qualified, the qualifiers are ignored)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • type intégral
    Original:
    integral type
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • énumération
    Original:
    enumeration
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • pointeur à l'objet ou à la fonction
    Original:
    pointer to object or to function
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • référence lvalue pour objet ou pour fonctionner
    Original:
    lvalue reference to object or to function
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • pointeur vers l'objet membre ou un membre de fonction
    Original:
    pointer to member object or to member function
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • std::nullptr_t (depuis C++11)
Les types de tableaux et la fonction peut être écrite dans une déclaration de modèle, mais elles sont automatiquement remplacé par le pointeur de données et un pointeur de fonction selon le cas .
Original:
Array and function types may be written in a template declaration, but they are automatically replaced by pointer to data and pointer to function as appropriate.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Lorsque le nom d'un paramètre de modèle non-type est utilisé dans une expression dans le corps du modèle de classe, c'est un prvalue non modifiable sauf si son type est un type référence lvalue .
Original:
When the name of a non-type template parameter is used in an expression within the body of the class template, it is an unmodifiable prvalue unless its type was an lvalue reference type.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[modifier] Tapez paramètre de modèle

typename name (1)
class name (2)
typename|class name = default (3)
typename|class ... name (4) (depuis C++11)
1)
Un paramètre de modèle type avec un nom facultatif
Original:
A type template parameter with an optional name
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
Exactement la même chose que 1)
Original:
Exactly the same as 1)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3)
Un paramètre de modèle type avec un nom facultatif et par défaut
Original:
A type template parameter with an optional name and a default
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
5)
Un modèle de type Paquet de paramètre avec un nom facultatif
Original:
A type template Paquet de paramètre with an optional name
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[modifier] Paramètre template template

template < parameter-list > name (1)
template < parameter-list > name = default (2)
template < parameter-list > ... name (3) (depuis C++11)
1)
Un paramètre de modèle modèle avec un nom facultatif
Original:
A template template parameter with an optional name
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
Un paramètre template modèle avec un nom et une option par défaut
Original:
A template template parameter with an optional name and a default
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3)
Un modèle de Paquet de paramètre modèle avec un nom facultatif
Original:
A template template Paquet de paramètre with an optional name
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[modifier] Instanciation du modèle de classe

Un modèle de classe en elle-même n'est pas un type ou un objet, ou toute autre entité. Aucun code est généré à partir d'un fichier source qui contient les définitions de modèle seulement. Pour tout code d'apparaître, un modèle doit être instancié: les arguments de modèle doit être assurée afin que le compilateur peut générer une classe réelle (ou d'une fonction, d'un modèle de fonction) .
Original:
A class template by itself is not a type, or an object, or any other entity. No code is generated from a source file that contains only template definitions. In order for any code to appear, a template must be instantiated: the template arguments must be provided so that the compiler can generate an actual class (or function, from a function template).
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[modifier] Instanciation explicite

template class name < argument-list > ; (1)
extern template class name < argument-list > ; (2) (depuis C++11)
1)
Définition instanciation explicite
Original:
Explicit instantiation definition
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
Déclaration instanciation explicite
Original:
Explicit instantiation declaration
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Une définition explicite d'instanciation forces instanciation de la classe, struct ou union ils se réfèrent. Il peut apparaître n'importe où dans le programme après la définition du modèle, et pour une donnée argument-list, est seulement autorisé à apparaître qu'une seule fois dans le programme .
Original:
An explicit instantiation definition forces instantiation of the class, struct, or union they refer to. It may appear in the program anywhere after the template definition, and for a given argument-list, is only allowed to appear once in the program.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Une déclaration instanciation explicite (un modèle externe) empêche les instanciations explicites: le code qui entraînerait autrement une instanciation implicite doit utiliser la définition instanciation explicite fournie ailleurs dans le programme .
Original:
An explicit instantiation declaration (an extern template) prevents implicit instantiations: the code that would otherwise cause an implicit instantiation has to use the explicit instantiation definition provided somewhere else in the program.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[modifier] Instanciation implicite

Lorsque le code se réfère à un modèle dans un contexte qui nécessite un type complètement définie, ou lorsque l'intégralité du type affecte le code, et ce type particulier n'a pas été explicitement instancié, l'instanciation implicite se produit. Par exemple, quand un objet de ce type est construit, mais pas quand un pointeur vers ce type est construit .
Original:
When code refers to a template in context that requires a completely defined type, or when the completeness of the type affects the code, and this particular type has not been explicitly instantiated, implicit instantiation occurs. For example, when an object of this type is constructed, but not when a pointer to this type is constructed.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Cela vaut pour les membres de la classe template: à moins que le membre est utilisée dans le programme, il n'est pas instancié, et ne nécessite pas une définition .
Original:
This applies to the members of the class template: unless the member is used in the program, it is not instantiated, and does not require a definition.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

template<class T> struct Z {
    void f() {}
    void g(); // never defined
}; // template definition
template struct Z<double>; // explicit instantiation of Z<double>
Z<int> a; // implicit instantiation of Z<int>
Z<char>* p; // nothing is instantiated here
p->f(); // implicit instantiation of Z<char> and Z<char>::f() occurs here.
// Z<char>::g() is never needed and never instantiated: it does not have to be defined

[modifier] Les paramètres des modèles non-type

Les limitations suivantes s'appliquent lors de l'instanciation des modèles de classe qui ont des paramètres de modèles non-type:
Original:
The following limitations apply when instantiating class templates that have non-type template parameters:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • Pour les types entiers et le calcul, l'argument modèle fourni lors de l'instanciation doit être une expression constante .
    Original:
    For integral and arithmetic types, the template argument provided during instantiation must be a constant expression.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Pour les pointeurs vers les objets, les arguments de modèle doivent désigner l'adresse d'un objet avec la durée de stockage statique et un lien (interne ou externe), ou une expression constante qui renvoie la valeur de pointeur null approprié .
    Original:
    For pointers to objects, the template arguments have to designate the address of an object with static storage duration and a linkage (either internal or external), or a constant expression that evaluates to the appropriate null pointer value.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Pour les pointeurs vers les fonctions, les arguments valides sont des pointeurs vers des fonctions avec liens (ou des expressions constantes qui permettent d'évaluer la valeur null valeurs de pointeur) .
    Original:
    For pointers to functions, the valid arguments are pointers to functions with linkage (or constant expressions that evaluate to null pointer values).
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Pour les paramètres de référence lvalue, l'argument fourni à l'instanciation ne peut pas être une mesure temporaire, un anonyme lvalue, ou un nom lvalue sans lien .
    Original:
    For lvalue reference parameters, the argument provided at instantiation cannot be a temporary, an unnamed lvalue, or a named lvalue with no linkage.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Pour des pointeurs vers les membres, l'argument doit être un pointeur vers le membre exprimée en &Class::Member ou une expression constante qui prend la valeur null valeur de pointeur .
    Original:
    For pointers to members, the argument has to be a pointer to member expressed as &Class::Member or a constant expression that evaluates to null pointer value.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
En particulier, cela implique que les chaînes littérales, les adresses des éléments du tableau, et les adresses des membres non statiques ne peuvent pas être utilisés comme arguments de modèle d'instancier des modèles dont les paramètres des modèles non correspondante de type sont des pointeurs vers les données .
Original:
In particular, this implies that string literals, addresses of array elements, and addresses of non-static members cannot be used as template arguments to instantiate templates whose corresponding non-type template parameters are pointers to data.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[modifier] Exemple

[edit]
template<typename T>
struct S {
    template<typename U> void foo(){}
};
 
template<typename T>
void bar()
{
    S<T>s;
    s.foo<T>(); // error: < parsed as less than operator
    s.template foo<T>(); // OK
}


[modifier] Les paramètres des modèles non-type

#include <iostream>
 
// simple non-type template parameter
template<int N>
struct S {
    int a[N];
};
 
template<const char*>
struct S2 {};
 
// complicated non-type example
template <
    char c, // integral type
    int (&ra)[5], // lvalue reference to object (of array type)
    int (*pf)(int), // pointer to function
    int (S<10>::*a)[10] // pointer to member object (of type int[10])
> struct Complicated {
    // calls the function selected at compile time
    // and stores the result in the array selected at compile time
    void foo(char base) {
        ra[4] = pf(c - base);
    }
};
 
//  S2<"fail"> s2; // Error: string literal cannot be used
char okay[] = "okay"; // static object with linkage
// S2< &okay[0] > s2; // Error: array element has no linkage
S2<okay> s2; // works
 
int a[5];
int f(int n) { return n;}
int main()
{
    S<10> s; // s.a is an array of 10 int
    s.a[9] = 4;
 
    Complicated<'2', a, f, &S<10>::a> c;
    c.foo('0');
 
    std::cout << s.a[9] << a[4] << '\n';
}

Résultat :

42

[modifier] Voir aussi