[cpp]: concept --<template>

发布时间 2024-01-12 11:19:22作者: lnlidawei

[cpp]:  concept --<template>

 

 

 

 

一、说明

 

  1、concept 定义一个“C”,“C”是一组“模板参数T”的限制条件。“C”:只有满足限制条件“C”模板的参数T,才能通过编译。

 

  2、代码示例

 1 // 定义概念“C1”
 2 
 3 template<class T>
 4 concept C1 = ( sizeof(T) > 4 || sizeof(T) <= 4 );
 5 
 6 
 7 
 8 
 9 // 应用概念“C1”: 模板函数
10 
11 template<C1 U>
12 void
13 fun()
14 {}
15 
16 
17 
18 
19 案例说明:
20 
21     1、定义概念:    concept是‘关键字’,用于定义概念。
22     
23     2、定义概念:    “C1”是概念“名字”,C1是一组模板参数的限制条件。
24     
25     3、应用概念:    template<C1 U>, 只有满足条件“C1”的U,才能通过编译。
26     
27     4、C1<U>涵义: 模板参数U,必须满足概念(条件)C1;  template<C1 U> == C1<U>    。

 

 

 

二、代码

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 
 5 
 6 using namespace std;
 7 
 8 
 9 class object{};
10 
11 
12 // concetp 'C1'('C1' constrains 'T'); 'T' is placeholder of type.  'C1<T>': 'T' is satisfied by the ruler of 'C1'
13 template<class T>
14 concept C1 = ( sizeof(T) > 4 || sizeof(T) <= 4 );
15 
16 
17 template<C1 T>
18 void
19 fun(string s)
20 {
21     cout << "[os]: fun("<< s <<")" << endl;
22 }
23 
24 
25 void run()
26 {
27     fun<int>("int");
28     fun<double>("doubule");
29     fun<object>("object");
30   
31 }
32 
33 
34 int main()
35 {
36     run();
37     return 0;
38 }

 

 

 

三、运行结果

1 g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
2 
3 [os]: fun(int)
4 [os]: fun(doubule)
5 [os]: fun(object)

 

 

 

四、参考文献

 

  1、  Template parameters  --  https://en.cppreference.com/w/cpp/language/template_parameters#Type_template_parameter

 

  2、  Constraints and concepts  --  https://en.cppreference.com/w/cpp/experimental/constraints

 

  3、  Constraints and concepts (since C++20)  --  https://en.cppreference.com/w/cpp/language/constraints

 

  4、  cpp 在线编译工具  --  https://coliru.stacked-crooked.com/