CPP Templates 之 模板的顯式特化技巧

來源:互聯網
上載者:User
模板的顯式特化的注意事項:

一、
指定的模板實參列表必須喝相應的模板參數列表一一對應。例如,我們不能用一個
非類型值來替換一個模板參數。然而,如果模板參數具有預設模板實參,那麼用來替換的

模板實參就是可選的:

template <typename T>
class Types{
public:
    typedef int I;
};

template <typename T,typename U=typename Types<T>::I>
class S;

template<>
class S<void>//ok
{
public:
    void f();
};

template<>
class S<char,char>;//ok

template<>

template<> class S<char,0>;//error.不能用0來代替U

二、全域成員特化

#include <iostream>

using namespace std;

template<typename T>
class Outer{/1
public:
    template<typename U>
    class Inner
    {
    private:
        static int count;
    };
    static int code;//4
    void print()const//5
    {
        std::cout<<"generic"<<endl;
    }
}
/*在4處的code和5處print(),這兩個普通成員都具有一個外圍類模板,因此需要用一個
 *template<>首碼說明:後面將用一個模板實參集來對他進行全域特化
 */
template<>
int Outer<void>::code=12;

template<>
void Outer<void>::print() const
{
    std::cout<<"Outer<void>"<<endl;
}
/*1.上面的這些定義會用於代替類Outer<void>在4和5處的泛型定義;但是類Outer<void>的
 *其他成員仍然預設地產生於1處的模板。
 *2.在提供了上述聲明後,就不能再次提供Outer<void>的顯示特化
 */

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.