赞
踩
C++20引入了concept,其一个主要的作用是用于模板对其参数所需满足的条件进行约束和说明。
比如,我们之前定义模板函数可能会遇到这样的问题:
- #include <iostream>
- using namespace std;
-
- template<class T>
- void test(T t)
- {
- t.p();
- }
-
- class A{
- public:
- void p()
- {
- cout<<"this is A::p"<<endl;
- }
- };
-
- int main()
- {
- A a;
- test(a);
- return 0;
- }

当模板实参的类型有成员函数p的时候,可以很好的工作
运行程序输出:this is A::p
但如果模板实参不满足条件:
- #include <iostream>
- using namespace std;
-
- template<class T>
- void test(T t)
- {
- t.p();
- }
-
- int main()
- {
- test(1);
- return 0;
- }
test的参数1是个整数,没有成员函数p
编译错误:error: request for member 'p' in 't', which is of non-class type 'int'
可以通过enable_if对模板所需满足的条件进行约束:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。