C++函數模板複習

來源:互聯網
上載者:User

標籤:

#include <iostream>
#include <typeinfo>
using namespace std;


template <class T>
T add(T one, T two)
{
    cout << "類型:" << typeid(T).name() << endl;
    return one + two; // 函數模板只有在調用時才編譯,有的編譯器在初次編譯時間就會編譯
}


int add(int one, int two)
{
    cout << "自訂int" << endl;
    return one + two;
}


template <class T, class F> //函數模板不僅可以接受資料類型,還可以接受操作類型
void show(T t, F f)
{
    f(t);
}
void show_(int temp)
{
    cout << temp << endl;
}


template<class T1, class T2>
auto temp1(T1 t1, T2 t2)->decltype(t1+t2) //自動型別推斷
{
    return t1 + t2;
}


template<class T>
void temp2(T t)
{
    decltype(t) d; //建立一個與T類型相同的變數
}


int main()
{
    //cout << add(1.2, 1.2) << endl;
    //cout << add(1, 2) << endl; //如果有自訂函數 int add(int, int),則會優先使用自訂的,不然會使用函數模板
    //cout << add<int>(1,2) << endl; //如果函數模板執行個體化,則無論有沒有自訂函數add,都會使用函數模板


    //show(1, show_);
    //show(1, [](int i){cout << i << " lambda" << endl;}); //可以把lambda運算式作為操作類型傳給函數模板


    //int a = 10;
    //decltype(a) b = 3; //decltype的功能是拷貝資料類型


    //cout << temp(1.2, 1) << endl;
    //cout << temp(1, 1.2) << endl;


    return 0;
}

C++函數模板複習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.