好处

  1. 相比typedef可读性更强
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>


using namespace std;

using PrintFunc = void(*)(std::string);

void Print(std::string s)
{

cout << s << endl;
}

int main(int argc, char* argv[])
{

PrintFunc f = Print;

f("Hello world");

return 0;
}
  1. 可以支持template
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <memory>


using namespace std;

template<typename T>
using deleted_unique_ptr = std::unique_ptr<T, std::function<void(T *)>>;

int main(int argc, char *argv[])
{

deleted_unique_ptr<FILE> file(fopen("test", "w"),
[](FILE * f) {
cout << __PRETTY_FUNCTION__ << endl;
fclose(f);
});
fputs("Hello world", file.get());

return 0;
}

参考

  1. http://stackoverflow.com/questions/10747810/what-is-the-difference-between-typedef-and-using-in-c11
  2. http://stackoverflow.com/questions/19053351/how-do-i-use-a-custom-deleter-with-a-stdunique-ptr-member

留言

2016-05-07