类模板使用示例(三) 类模板局部特化

时间:2021-12-06 17:06:08

MyClass.h文件代码:

#ifndef MYCLASS_H
#define MYCLASS_H

#include<iostream>

template <typename T1, typename T2>
class MyClass
{
public:
    void print()
    {
        std::cout << "T1 VS. T2" << std::endl;
    }
};

template <typename T>
class MyClass<T, T>
{
public:
    void print()
    {
        std::cout << "T VS. T" << std::endl;
    }
};

template <typename T>
class MyClass<T, int>
{
    public:
    void print()
    {
        std::cout << "T VS. int" << std::endl;
    }
};


template <typename T1, typename T2>
class MyClass<T1*, T2*>
{
    public:
    void print()
    {
        std::cout << "T1* VS. T2*" << std::endl;
    }
};

template <typename T>
class MyClass<T*, T*>
{
    public:
    void print()
    {
        std::cout << "T* VS. T*" << std::endl;
    }
};

#endif // MYCLASS_HPP_INCLUDED

 

测试用代码main.cpp:

#include <iostream>
#include <string>
#include <cstdlib>
#include "MyClass.h"

using namespace std;

int main()
{
    MyClass<int, float> mcif;
    mcif.print();

    MyClass<float,float> mcff;
    mcff.print();

    MyClass<float, int> mcfi;
    mcfi.print();

    MyClass<int*, float*> mcipfp;
    mcipfp.print();

    MyClass<int*, int*> mcipip;
    mcipip.print();

    //MyClass<int, int> mcii;// Will cause ambiguous class template instantiation

    return 0;
}

结果:

类模板使用示例(三) 类模板局部特化