Home >Backend Development >C++ >What is ODR-Use in C Class Template Member Functions?

What is ODR-Use in C Class Template Member Functions?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 11:44:11980browse

What is ODR-Use in C   Class Template Member Functions?

Understanding ODR-Use in C

In the context of C programming, the concept of "odr-use" often arises when discussing class template member functions.

The One Definition Rule (ODR) ensures that there is a single, consistent definition for every entity across all translation units in a program. ODR-use defines when an entity must have a definition provided, as opposed to simply a declaration.

According to the C standard, a non-overloaded function is odr-used if:

  • Its name appears in a potentially evaluated expression.
  • It is a member of a set of candidate functions selected by overload resolution.
  • It is a non-pure virtual function.

ODR-Use and Class Template Member Functions

For class template member functions, the ODR-use rule means that they will only be instantiated if they are:

  • Called explicitly.
  • Virtual and the class itself is instantiated (even if the function is not called).

This rule ensures that template member functions are only instantiated when they are actually needed. By default, the compiler will not instantiate unused member functions, saving compilation time.

ODR-Use and Multiple Compilation Units

When using multiple compilation units, the compiler must ensure that all odr-used entities are defined exactly once. It achieves this through the concept of "primary templates." A primary template is the first instantiation of a template in a translation unit. All subsequent template instantiations in other translation units are considered secondary instantiations.

The primary template is responsible for providing the definition of odr-used entities. If a member function is odr-used but is not called within the primary template, it must still be declared with a definition to satisfy the ODR.

Instantiating All Member Functions

Explicitly instantiating a class template guarantees instantiation of all member functions, including odr-used functions that are not called. This ensures that the complete definition is available for all compilation units, avoiding potential linkage errors. However, it is not always necessary or efficient to instantiate unused member functions.

The above is the detailed content of What is ODR-Use in C Class Template Member Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn