????????C++11?????????????????漰??template???????????
????????toy code??????????????????o?????????
????function
????C++????????????????????????????lambda????????operator()?????????????????????Щ???????????????????????????????е??
int add(int i?? int j) { return i + j; }
struct divide
{
int operator()(int i?? int j)
{
return i / j;
}
};
std::map<std::string?? int(*)(int?? int)>> binops = {
{"+"?? add}??
{"-"?? std::minus<int>()}??
{"*"?? [](int i?? int j) {return i * j; }}??
{"/"?? divide()}??
};?????????????????
???????????binops?е????????????????int(*)(int?? int)??
????C++11?±??????????????function??????????????function????????????е?????????????Щ????????????????????????????μ??
std::cout<<"test function<T>: ";
std::map<std::string?? std::function<int(int?? int)>> binops = {
{"+"?? add}??
{"-"?? std::minus<int>()}??
{"*"?? [](int i?? int j) {return i * j; }}??
{"/"?? divide()}??
};
std::cout<<"+: "<<binops["+"](1?? 2)<<" ";
std::cout<<"-: "<<binops["-"](1?? 2)<<" ";
std::cout<<"*: "<<binops["*"](1?? 2)<<" ";
std::cout<<"/: "<<binops["/"](1?? 2)<<" ";
std::cout<<"test function<T> done. "<<std::endl;
??????????
???????±???У??????????????????????????????????
template<typename T> class Bar
{
friend T;
protected:
int val = 100;
};
class Foo
{
public:
void print_bar(Bar<Foo> &bar) {std::cout<<"bar: "<<bar.val<<std::endl;}
};
std::cout<<"test friend template type: ";
Bar<Foo> bar;
Foo foo;
foo.print_bar(bar);
std::cout<<"test friend template type done. "<<std::endl;
???????????????????????????Foo?п??????????Bar??protected?????
??????????
?????±???У????????using??????????????
????template<typename T> using twin = std::pair<T?? T>;
????template<typename T> using str_int = std::pair<T?? int>;
????std::cout<<"test template alias: ";
????twin<std::string> twin_str = {"abc"?? "def"};
????std::cout<<"twin_str: "<<twin_str.first<<' '<<twin_str.second<<std::endl;
????str_int<std::string> strno = {"abc"?? 100};
????std::cout<<"strno: "<<strno.first<<' '<<strno.second<<std::endl;
????std::cout<<"test template alias done. "<<std::endl;
???????????????????str_int?????????????????????????????塣??????????????????
??????????
?????±???У????????????????????????????????????????
????template<typename T?? typename F=std::less<T>>
????int compare(const T &v1?? const T &v2?? F f=F())
????{
????if(f(v1?? v2)) return -1;
????if(f(v2?? v1)) return 1;
????return 0;
????}
????std::cout<<"test default template parameter: ";
????std::cout<<"compare int 1 2: "<<compare(1?? 2)<<std::endl;
????std::cout<<"compare int 2.0 1.0: "<<compare(2.0?? 1.0)<<std::endl;
????//std::cout<<"compare int 2.0 1: "<<compare(2.0?? 1)<<std::endl; // wrong. can't determine which type is T
????std::cout<<"test default template parameter done. "<<std::endl;
????β?÷???????