Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

เทมเพลตและตัวแปร Static ใน C++

เทมเพลตและตัวแปร Static ใน C++ (Templates and Static Variables)

ใน C++ สำหรับ function templates และ class templates แต่ละ instance (การสร้างเฉพาะ型) จะมีตัวแปร static ตัวของมันเอง (แยกจาก instance อื่น)

ตัวอย่าง

#include <iostream>
using namespace std;

template <typename T>
void fun(const T& x) {
    static int i = 10;
    cout << ++i;
    return;
}

int main() {
    fun<int>(1);    // พิมพ์ 11
    cout << endl;
    fun<int>(2);    // พิมพ์ 12 (static i เดียวกันกับ fun<int>)
    cout << endl;
    fun<double>(1.1); // พิมพ์ 11 อีกครั้ง (static i ใหม่สำหรับ fun<double>)
    cout << endl;
    return 0;
}

ผลลัพธ์

11
12
11

คำอธิบาย

  • fun<int> และ fun<double> เป็น template instances ที่ต่างกัน
  • แต่ละ instance มี static int i ตัวของตัวเอง
  • การเรียก fun<int> ครั้งแรก: i=10→11, ครั้งที่สอง: i=11→12
  • การเรียก fun<double> ใช้ i ใหม่เริ่มที่ 10→11

ข้อสังเกตสำคัญ

  • Static variable ใน template function จะถูกสร้างแยกกันสำหรับแต่ละ template argument
  • นี่แตกต่างจาก static variable ใน regular function ที่มีเพียงตัวเดียวสำหรับทั้งโปรแกรม