Effective C++ .47 traits与模板特化

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

template<class T, class P>
T mul(T a, P b) {
    return a * b;
}

template<>
string mul<string, int>(string a, int b) {
    string res;
    for (int i=b; i>0; i--) {
        res.append(a);
    }
    return res;
}

int main() {
    cout<<mul(123,2)<<endl;
    
    cout<<mul(string("haha"),2)<<endl;
    return 0;
}

 traits对于基本类型可以采用特化方式为其'添加'一些属性(因为原本基本类型没有也不能在加入自定义的属性)

原文地址:https://www.cnblogs.com/lailailai/p/4180220.html