函数模板示例(二) 全特化示例

函数的定义function2.h:

#ifndef FUNCTION2_H
#define FUNCTION2_H

#include <string>
#include <cstring>
#include <iostream>

template <typename T>
T myMax(const T p1, const T p2)
{
    std::cout << "default func" << std::endl;
    return p1 < p2 ? p2 : p1;
}

template <>
const char* myMax(const char* str1, const char* str2)
{
    std::cout << "char* func" << std::endl;
    return (std::strcmp(str1, str2) < 0) ? str2 : str1;
}


#endif // FUNCTION2_H

 

测试文件main.cpp:

#include <iostream>
#include "function2.h"

using namespace std;

int main()
{
    cout << myMax(20, 30) << endl;
    cout << myMax("Hello", "World") << endl;

    return 0;
}

 

结果:

posted @ 2015-04-22 22:26  motein  阅读(243)  评论(0编辑  收藏  举报