gpt4 book ai didi

c++ - 用于确保设计契约(Contract)的 static_assert

转载 作者:可可西里 更新时间:2023-11-01 16:34:42 27 4
gpt4 key购买 nike

作为开发人员团队的一员,我想确保在我们发布的自定义迭代器上实现一组函数(和运算符)。使用 STL 迭代器类型作为基类型会有所帮助,但是由于某些原因(超出我的控制范围),我们决定不强制执行 STL 兼容性。迭代器由同一个团队和整个公司的人员使用。

我想设计一个使用迭代器类型并根据设计契约进行测试的模板类。

例如,我希望迭代器实现 operator++ 、 operator-- 并声明所需的 typedef。

1> 是否可以实现这样一个强制设计契约的模板类?可能使用 static_assert ?

2> 如果是,这是一个好的设计吗?

引用:custom iterator

最佳答案

Is it possible to implement such a template class that enforces the design contract ? probably using static_assert ?

用于检查特定方法是否存在(非常类似于 this example ):

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

is this a good design ?

是的,因为通过中断构建,错误很快就会被捕获,类的用户不必阅读文档(大多数人在编程时通常会跳过那部分)

关于c++ - 用于确保设计契约(Contract)的 static_assert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12509962/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com