#include <iostream>
/** using语法与typedef一样,并不会创建出新的类型,它们只是给
* 某些类型定义新的别名,using相比较typedef优势在于定义函数指针别名时看起来
* 更加直观,并且可以给模板定义别名
*/
template <typename T>
using myMap = std::map<int, T>;
void Test()
{
myMap<int> map1;
map1.insert(std::make_pair<int, int>(1, 2));
map1.insert(std::make_pair<int, int>(1, 2));
myMap<std::string> map2;
map2.insert(std::make_pair<int, std::string>(1, "2"));
}
// 使用typedef模板类型,需要使用struct包裹下,using 相比简单些
template <typename T>
struct STMap
{
typedef std::map<int, T> myMap;
};
void Test1()
{
STMap<int>::myMap map1;
map1.insert(std::make_pair<int, int>(1, 2));
map1.insert(std::make_pair<int, int>(1, 2));
myMap<std::string> map2;
map2.insert(std::make_pair<int, std::string>(1, "2"));
}
// typedef 模板函数指针
template <typename T>
struct STFunc{
typedef T(*type)(T, T);
};
int add(int l, int r) {
return (l)+(r);
}
double add(double l, double r) {
return (l)+(r);
}
void Test2(){
STFunc<int>::type func1 = add;
std::cout<<func1(1,2)<<std::endl;
STFunc<double>::type func2 = add;
std::cout<<func2(1,2.1)<<std::endl;
}
// using 通过赋值语法来定义类型别名
template<typename T>
using funcType = T(*)(T,T); // using
void Test3(){
funcType<int> func1 = add;
std::cout<<func1(1,2)<<std::endl;
funcType<double> func2 = add;
std::cout<<func2(1,2.1)<<std::endl;
}
// 2.using用在命名空间中,using namespace std; // 表明使用的是std命名空间中的函数,cout,map, stack
// 3.用在类中
// 4.用在类型别名
void Test4(){
using int_t = int;
int_t = 10;
}
// 5.定义函数指针
typedef int(*func)(int a, int b);
using func1=int(*)(int a, int b)
void Test5(){
func fun_ptr_var1 = add(1,2);
func1 fun_ptr_var2 = add(1,2);
}
int main() {
Test1();
Test2();
}
C++ 新特性using
于 2022-03-05 23:34:08 首次发布