Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

C++: Should I use 'typedef' or 'using namespace'?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The two options you state are not equivalent. This one:

using namespace project1::namespace1;

pulls in everything from the namespace, giving you little control and making clashes likely. I see only cons, and no pros here.

But you don't need to use a typedef to bring in a single symbol, you can use

using project1::namespace1::class1;

Whether you use this or the typedef doesn't make too much of a difference. But bear in mind that typedef is limited to types and enumerations, whereas using can refer to values, functions, etc:

namespace X {
  const int x{42};
  enum Fruit{Apple, Pear};
}

using X::x; // OK
typedef X::x xx; // Error! 'x' in namespace 'X' does not name a type

so the two expressions are not completely equivalent.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...