当前位置:   article > 正文

C++(20):concept概念_concept用法cpp

concept用法cpp

C++20引入了concept,其一个主要的作用是用于模板对其参数所需满足的条件进行约束和说明。

比如,我们之前定义模板函数可能会遇到这样的问题:

  1. #include <iostream>
  2. using namespace std;
  3. template<class T>
  4. void test(T t)
  5. {
  6. t.p();
  7. }
  8. class A{
  9. public:
  10. void p()
  11. {
  12. cout<<"this is A::p"<<endl;
  13. }
  14. };
  15. int main()
  16. {
  17. A a;
  18. test(a);
  19. return 0;
  20. }

当模板实参的类型有成员函数p的时候,可以很好的工作
运行程序输出:

this is A::p

但如果模板实参不满足条件:

  1. #include <iostream>
  2. using namespace std;
  3. template<class T>
  4. void test(T t)
  5. {
  6. t.p();
  7. }
  8. int main()
  9. {
  10. test(1);
  11. return 0;
  12. }

test的参数1是个整数,没有成员函数p

编译错误:error: request for member 'p' in 't', which is of non-class type 'int'

可以通过enable_if对模板所需满足的条件进行约束:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/208396
推荐阅读
相关标签
  

闽ICP备14008679号