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
319 views
in Technique[技术] by (71.8m points)

c++ - Using strong typedef as a more lightweight alternative to Boost Parameter library?

I often use the Boost strong typedef utility to improve the safety of my programs. For example by writing code like this:

BOOST_STRONG_TYPEDEF(int, X)
BOOST_STRONG_TYPEDEF(int, Y)
BOOST_STRONG_TYPEDEF(int, Width)
BOOST_STRONG_TYPEDEF(int, Height)

struct Rect {
    Rect(X x, Y y, Width w, Height h);
};

// Usage:
Rect rect(X(10), Y(20), Width(800), Height(600));

The strong typedef here improves both code readability and safety. (The compiler will report an error if the arguments are provided in the wrong order, which would not have been the case if the arguments were all int.)

My questions are:

  • Is it ok to use BOOST_STRONG_TYPEDEF for this purpose? (The documentation is very brief.)
  • Are there important reasons to prefer the boost parameter library instead?
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Technically speaking:

  • it works
  • it adds type safety

Practically speaking:

I would not recommend creating new types just for the sake of a single function's parameters (unless it is an enum specific to this function), types should permeate the application to avoid casts being used over and over.

If the types X, Y, Width and Height are used throughout the application, then not only will there be no cast, but your application will be much safer and much better documented too (yeah... I am a type freak).

Now, with regard to Boost.Parameters, this is completely different.

Boost.Parameters can (potentially) be added when you have types already in place. Honestly though I never saw the need. When your functions grow so unwieldy that Boost.Parameters is required to call them, you should fix the functions, not add to the clutter.


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

...