作为开发人员团队的一员,我想确保在我们发布的自定义迭代器上实现一组函数(和运算符).使用STL迭代器类型作为基本类型有帮助,但是由于某些原因(在我的控制范围之外),我们决定不强制执行STL兼容性.迭代器由同一团队和整个公司的人员使用.
我想设计一个消耗迭代器类型的模板类,并根据设计合同进行测试.
例如,我希望迭代器实现一个operator ++,operator--并声明所需的typedef.
1>是否可以实现强制设计合同的模板类?可能使用static_assert?
2>如果是,这是一个好的设计吗?
reference:自定义迭代器
BЈо*_*вић 11
是否可以实现强制设计合同的模板类?可能使用static_assert?
用于检查是否存在特定方法(与此示例非常相似):
struct Hello
{
};
struct Generic {
int operator++()
{
return 5;
}
};
// SFINAE test
template <typename T>
class has_operator_plusplus
{
typedef char one;
typedef long two;
template <typename C> static one test( decltype(&C::operator++) ) ;
template <typename C> static two test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};
int main(int argc, char *argv[])
{
// the first check breaks the build
//static_assert( has_operator_plusplus<Hello>::value, "has no operator" );
static_assert( has_operator_plusplus<Generic>::value, "has no operator" );
}
Run Code Online (Sandbox Code Playgroud)
这是一个很好的设计吗?
是的,因为通过打破构建,错误被捕获得非常快,并且类的用户不必阅读文档(大多数人通常在编程时跳过该部分)