使用强 typedef 作为 Boost Parameter 库的更轻量级的替代品?

2021-12-24 00:00:00 c++ boost boost-parameter

我经常使用 Boost strong typedef 实用程序来提高我的程序的安全性.例如通过编写这样的代码:

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));

这里的强 typedef 提高了代码的可读性和安全性.(如果参数以错误的顺序提供,编译器会报错,如果参数都是int,则不会出现这种情况.)

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.)

我的问题是:

  • 为此目的可以使用 BOOST_STRONG_TYPEDEF 吗?(文档非常简短.)
  • 是否有更喜欢 boost 参数库的重要原因?

推荐答案

技术上:

  • 有效
  • 它增加了类型安全

实际上:

我不建议仅仅为了单个函数的参数而创建新类型(除非它是特定于该函数的枚举),类型应该渗透到应用程序中以避免反复使用强制转换.

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.

如果在整个应用程序中使用 XYWidthHeight 类型,那么不仅会不会没有演员表,但你的应用程序会更安全,文档也会更好(是的......我是一个类型怪胎).

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).

现在,关于 Boost.Parameters,这是完全不同的.

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

Boost.Parameters 可以(可能)在您已经有类型时添加.老实说,虽然我从来没有看到需要.当您的函数变得如此笨拙以至于需要 Boost.Parameters 来调用它们时,您应该修复这些函数,而不是添加到混乱中.

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.

相关文章