C++11的using与typedef的区别(The difference between using and typedef in C + + 11)

两者都是给类型设置一个别名,区别是using可以给模板类设置别名,而typedef则不能模板类设置设置别名。其余情况没有什么区别。

#include <vector>
using namespace std;

template<typename T>
using myvector=vector<T>;

int main(){
  myvector<int> iv;
  return 0;
}

编译通过。

#include <vector>
using namespace std;

template<typename T>
typedef vector<T> myvector;

int main(){
  myvector<int> iv;
  return 0;
}

编译报错。

error: template declaration of ‘typedef’

而已经推演过的模板类是可以用typedef设置别名的

#include <vector>
using namespace std;

typedef vector<int> intvector;

int main(){
  intvector iv;
  return 0;
}
————————

Both set an alias for the type. The difference is that using can set an alias for the template class, while typedef cannot set an alias for the template class. There is no difference in the rest.

#include <vector>
using namespace std;

template<typename T>
using myvector=vector<T>;

int main(){
  myvector<int> iv;
  return 0;
}

Compilation passed.

#include <vector>
using namespace std;

template<typename T>
typedef vector<T> myvector;

int main(){
  myvector<int> iv;
  return 0;
}

Compilation error.

error: template declaration of ‘typedef’

The template class that has been deduced can be aliased with typedef

#include <vector>
using namespace std;

typedef vector<int> intvector;

int main(){
  intvector iv;
  return 0;
}