(23条消息) 变参表达式_最后冰吻free的博客-CSDN博客

PHOTO EMBED

Thu Nov 24 2022 06:07:29 GMT+0000 (Coordinated Universal Time)

Saved by @leawoliu

#include <iostream>
#include <string>
#include <vector>
 
 template<typename First, typename... Args>
 void Print(First first, Args... args){
     std::cout<<first<<std::endl;
     if constexpr (sizeof...(args)> 0) {
         Print(args...);
     }
 }
 
 // 变参表达式
template<typename... Args>
void Double(Args... args){
    Print(args+args...); // 每个元素和自己进行相加运算
}


template<std::size_t V=1, typename... Args>
void DoubleOne(Args... args){
     Print(args+V ...); // 每个元素加上指定value
    // Print(args+1 ...); // 省略号... 与数字1之间必须有空格
    // Print((args+1)...); // 或者表达式括起来
}



void Test(){
    Double(1,2,3,4); // 2,4,6,8 每个元素进行翻倍
    Double(std::string("hello"), std::string("world"));// hellohello, worldworld, string相加
    
    DoubleOne<10>(1,2,3,4); // 11,12,13,14
}


// 变参各参数类型是否一样
template<typename First, typename... Args>
constexpr bool CheckIsSameType(First, Args...) {
    return (std::is_same<First, Args>::value && ...); // 使用折叠
}

void Test1(){
   std::cout<<std::boolalpha<<CheckIsSameType(1,2,3,4)<<std::endl; //true
   std::cout<<std::boolalpha<<CheckIsSameType(1,2,3,4.0)<<std::endl; //false
   
    
    // 按值传递,所有参数类型都被推断为char const*(发生类型decay退化),否则依次为char const[6], char const[2], char const[6], char const[2]
   std::cout<<std::boolalpha<<CheckIsSameType("hello", " ", "world", "!")<<std::endl; //true
}

int main()
{
    Test();
    Test1();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
content_copyCOPY

https://blog.csdn.net/CodeHouse/article/details/126343659