Rod*_*ddy 4 c++ templates boost class
我经常发现自己使用Integers来表示不同"空格"中的值.例如...
int arrayIndex;
int usersAge;
int daysToChristmas;
Run Code Online (Sandbox Code Playgroud)
理想情况下,我希望为"Index","Years"和"Days"这些类型中的每一种都设置单独的类,这样可以防止我意外混淆它们.从documnentation的角度来看,Typedef是一种帮助,但它不够类型安全.
我已经尝试过包装器类,但最终却有太多的样板供我喜欢.是否有一个简单的基于模板的解决方案,或者可能是Boost中准备好的东西?
编辑:有几个人在他们的答案中谈到边界检查.这可能是一个方便的副作用,但不是一个关键要求.特别是,我不仅想要防止越界分配,而且要防止"不适当"类型之间的分配.
您可以使用的一个时髦的"hack"是用于创建包装类型的模板非类型参数.这不添加任何界限,但它确实允许把它们作为不同类型的只有一套样板模板代码.即
template<unsigned i>
class t_integer_wrapper
{
private:
int m_value;
public:
// Constructors, accessors, operators, etc.
};
typedef t_integer_wrapper<1> ArrayIndex;
typedef t_integer_wrapper<2> UsersAge;
Run Code Online (Sandbox Code Playgroud)
根据需要使用下限和上限或其他验证扩展模板.虽然远远不是很漂亮.
我记得用一个简单的模板来解决类似的问题,你可以在其中指定允许的范围,即
Int<0, 365> daysToChristmas;
Int<0, 150> usersAge;
Int<0, 6> dayOfWeek;
Run Code Online (Sandbox Code Playgroud)
你明白了.现在你可以从这样的模板类型派生出来,比如
class DayOfYear: public Int<0, 365> {}
Run Code Online (Sandbox Code Playgroud)
并且您不能再将用户年龄传递给期望DayOfYear的函数,并且您不必使用有角度的括号.
你可以尝试BOOST_STRONG_TYPEDEF.来自boost/strong_typedef.hpp
:
// macro used to implement a strong typedef. strong typedef
// guarentees that two types are distinguised even though the
// share the same underlying implementation. typedef does not create
// a new type. BOOST_STRONG_TYPEDEF(T, D) creates a new type named D
// that operates as a type T.
Run Code Online (Sandbox Code Playgroud)