假设我有一个 LimitedValue 类,它保存一个值,并在 int 类型“min”和“max”上进行参数化。您可以将它用作保存只能在一定范围内的值的容器。你可以这样使用它:
LimitedValue< float, 0, 360 > someAngle( 45.0 );
someTrigFunction( someAngle );
这样 'someTrigFunction' 就知道保证提供了一个有效的输入(如果参数无效,构造函数会抛出异常)。
但是,复制构造和赋值仅限于完全相同的类型。我希望能够做到:
LimitedValue< float, 0, 90 > smallAngle( 45.0 );
LimitedValue< float, 0, 360 > anyAngle( smallAngle );
并在编译时检查该操作,因此下一个示例给出错误:
LimitedValue< float, -90, 0 > negativeAngle( -45.0 );
LimitedValue< float, 0, 360 > postiveAngle( negativeAngle ); // ERROR!
这可能吗?有没有一些实用的方法可以做到这一点,或者有什么例子可以做到这一点?
最佳答案
好的,这是没有 Boost 依赖的 C++11。
在编译时检查类型系统保证的所有内容,其他任何内容都会引发异常。
我为可能抛出的转换添加了 unsafe_bounded_cast
,为静态正确的显式转换添加了 safe_bounded_cast
(这是多余的,因为复制构造函数处理它,但提供对称性和表现力)。
使用示例
#include "bounded.hpp"
int main()
{
BoundedValue<int, 0, 5> inner(1);
BoundedValue<double, 0, 4> outer(2.3);
BoundedValue<double, -1, +1> overlap(0.0);
inner = outer; // ok: [0,4] contained in [0,5]
// overlap = inner;
// ^ error: static assertion failed: "conversion disallowed from BoundedValue with higher max"
// overlap = safe_bounded_cast<double, -1, +1>(inner);
// ^ error: static assertion failed: "conversion disallowed from BoundedValue with higher max"
overlap = unsafe_bounded_cast<double, -1, +1>(inner);
// ^ compiles but throws:
// terminate called after throwing an instance of 'BoundedValueException<int>'
// what(): BoundedValueException: !(-1<=2<=1) - BOUNDED_VALUE_ASSERT at bounded.hpp:56
// Aborted
inner = 0;
overlap = unsafe_bounded_cast<double, -1, +1>(inner);
// ^ ok
inner = 7;
// terminate called after throwing an instance of 'BoundedValueException<int>'
// what(): BoundedValueException: !(0<=7<=5) - BOUNDED_VALUE_ASSERT at bounded.hpp:75
// Aborted
}
异常支持
这有点样板,但提供了如上所述的相当可读的异常消息(如果您选择捕获派生的异常类型并可以用它做一些有用的事情,那么实际的最小/最大值/值也会暴露出来)。
#include <stdexcept>
#include <sstream>
#define STRINGIZE(x) #x
#define STRINGIFY(x) STRINGIZE( x )
// handling for runtime value errors
#define BOUNDED_VALUE_ASSERT(MIN, MAX, VAL) \
if ((VAL) < (MIN) || (VAL) > (MAX)) { \
bounded_value_assert_helper(MIN, MAX, VAL, \
"BOUNDED_VALUE_ASSERT at " \
__FILE__ ":" STRINGIFY(__LINE__)); \
}
template <typename T>
struct BoundedValueException: public std::range_error
{
virtual ~BoundedValueException() throw() {}
BoundedValueException() = delete;
BoundedValueException(BoundedValueException const &other) = default;
BoundedValueException(BoundedValueException &&source) = default;
BoundedValueException(int min, int max, T val, std::string const& message)
: std::range_error(message), minval_(min), maxval_(max), val_(val)
{
}
int const minval_;
int const maxval_;
T const val_;
};
template <typename T> void bounded_value_assert_helper(int min, int max, T val,
char const *message = NULL)
{
std::ostringstream oss;
oss << "BoundedValueException: !("
<< min << "<="
<< val << "<="
<< max << ")";
if (message) {
oss << " - " << message;
}
throw BoundedValueException<T>(min, max, val, oss.str());
}
值类
template <typename T, int Tmin, int Tmax> class BoundedValue
{
public:
typedef T value_type;
enum { min_value=Tmin, max_value=Tmax };
typedef BoundedValue<value_type, min_value, max_value> SelfType;
// runtime checking constructor:
explicit BoundedValue(T runtime_value) : val_(runtime_value) {
BOUNDED_VALUE_ASSERT(min_value, max_value, runtime_value);
}
// compile-time checked constructors:
BoundedValue(SelfType const& other) : val_(other) {}
BoundedValue(SelfType &&other) : val_(other) {}
template <typename otherT, int otherTmin, int otherTmax>
BoundedValue(BoundedValue<otherT, otherTmin, otherTmax> const &other)
: val_(other) // will just fail if T, otherT not convertible
{
static_assert(otherTmin >= Tmin,
"conversion disallowed from BoundedValue with lower min");
static_assert(otherTmax <= Tmax,
"conversion disallowed from BoundedValue with higher max");
}
// compile-time checked assignments:
BoundedValue& operator= (SelfType const& other) { val_ = other.val_; return *this; }
template <typename otherT, int otherTmin, int otherTmax>
BoundedValue& operator= (BoundedValue<otherT, otherTmin, otherTmax> const &other) {
static_assert(otherTmin >= Tmin,
"conversion disallowed from BoundedValue with lower min");
static_assert(otherTmax <= Tmax,
"conversion disallowed from BoundedValue with higher max");
val_ = other; // will just fail if T, otherT not convertible
return *this;
}
// run-time checked assignment:
BoundedValue& operator= (T const& val) {
BOUNDED_VALUE_ASSERT(min_value, max_value, val);
val_ = val;
return *this;
}
operator T const& () const { return val_; }
private:
value_type val_;
};
Actor 支持
template <typename dstT, int dstMin, int dstMax>
struct BoundedCastHelper
{
typedef BoundedValue<dstT, dstMin, dstMax> return_type;
// conversion is checked statically, and always succeeds
template <typename srcT, int srcMin, int srcMax>
static return_type convert(BoundedValue<srcT, srcMin, srcMax> const& source)
{
return return_type(source);
}
// conversion is checked dynamically, and could throw
template <typename srcT, int srcMin, int srcMax>
static return_type coerce(BoundedValue<srcT, srcMin, srcMax> const& source)
{
return return_type(static_cast<srcT>(source));
}
};
template <typename dstT, int dstMin, int dstMax,
typename srcT, int srcMin, int srcMax>
auto safe_bounded_cast(BoundedValue<srcT, srcMin, srcMax> const& source)
-> BoundedValue<dstT, dstMin, dstMax>
{
return BoundedCastHelper<dstT, dstMin, dstMax>::convert(source);
}
template <typename dstT, int dstMin, int dstMax,
typename srcT, int srcMin, int srcMax>
auto unsafe_bounded_cast(BoundedValue<srcT, srcMin, srcMax> const& source)
-> BoundedValue<dstT, dstMin, dstMax>
{
return BoundedCastHelper<dstT, dstMin, dstMax>::coerce(source);
}
关于c++ - 限制 C++ 中值类型的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/148511/