Home > Backend Development > C++ > How to Define and Initialize Static Data Members in C Class Templates?

How to Define and Initialize Static Data Members in C Class Templates?

Patricia Arquette
Release: 2024-12-02 08:36:14
Original
470 people have browsed it

How to Define and Initialize Static Data Members in C   Class Templates?

Defining Static Data Member in a Class Template

A need often arises to define a static data member within a class template. However, the traditional approach of defining the member within the class declaration is not feasible as it must be initialized outside the class definition due to non-integral data types. This poses a challenge, especially when the class is a template, prohibiting the definition from being placed in a separate compiled file.

To resolve this issue, a technique involves defining the static data member within the header file but initializing it outside in a separate definition. Here's an example:

template <typename T>
struct S
{
    static double something_relevant;
};

template <typename T>
double S<T>::something_relevant = 1.5;
Copy after login

In this approach, the static data member something_relevant is initially declared within the class template definition. Then, its initialization is performed outside in a separate definition, where it can be any non-integral data type. Since the definition is part of the template, the compiler ensures it is defined only once, avoiding multiple definitions.

The above is the detailed content of How to Define and Initialize Static Data Members in C Class Templates?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template