簡體   English   中英

c ++ 中的模板如何在后台實際工作?

[英]How does template in c ++ actually work in background?

** 為什么代碼的 output 是

  x = 1 count = 0

  x = 1 count = 1

 x = 1.1 count = 0

**

//code for template
#include <iostream>
using namespace std;

template <typename T>
void fun(const T&x)
{
    static int count = 0;
    cout << "x = " << x << " count = " << count << endl;
    ++count;
    return;
}

int main()
{
    fun<int> (1);//for int
    cout << endl;
    fun<int>(1);//for int
    cout << endl; 
    fun<double>(1.1);//for int
    cout << endl;
    return 0;
}

編譯器是否為上述代碼中 c++ 中的每種數據類型創建了模板 function 的新實例,以及在調用 function 時我們如何將右值分配給引用變量?

在您的代碼中,您使用模板創建了兩個函數,一個 function 使用int類型,另一個 function 使用double類型:

void fun(const int &x)
{
    static int count = 0;
    cout << "x = " << x << " count = " << count << endl;
    ++count;
    return;
}

void fun(const double &x)
{
    static int count = 0;
    cout << "x = " << x << " count = " << count << endl;
    ++count;
    return;
}

編譯器可以將第二個fun<int>(1)識別為對上述 integer function 的調用,因此不需要生成第三個 function。

通過引用或const引用傳遞template函數和普通函數一樣; template只影響數據類型,而不影響參數的傳遞方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM