我一直在寻找一个示例来展示如何在 C++ 中实现约束(或让我轻松做到这一点的 boost 库),但运气不佳。我能想到的最好的办法是:
#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
template<typename T>
class constrained
{
public:
constrained(boost::function<bool (T)> constraint, T defaultValue, T value = defaultValue)
{
ASSERT(constraint(defaultValue));
ASSERT(constraint(value));
this->value = value;
this->defaultValue = defaultValue;
this->constraint = constraint;
}
void operator=(const T &assignedValue)
{
if(constraint(assignedValue))
value = assignedValue;
}
private:
T value;
T defaultValue;
boost::function<bool (T)> constraint;
};
int main(int argc, char* argv[])
{
constrained<int> foo(boost::lambda::_1 > 0 && boost::lambda::_1 < 100, 5, 10);
foo = 20; // works
foo = -20; // fails
return 0;
}
当然,您可能希望约束类提供更多功能。这只是一个起点的想法。
无论如何,我看到的问题是我必须重载 T 定义的所有运算符,以使其真正表现得像 T,而我无法找出它们是什么。现在,我实际上不需要那么多不同类型的约束,所以我可以省略模板并硬编码它们。不过,我想知道是否有一个通用的(或至少更简洁/优雅的)解决方案,或者我的方法是否有任何严重错误。