C++ 基础 day2 C++17新特性
一.折叠表达式
C++17中引入了折叠表达式,主要是方便模板编程,分为左右折叠
语法
( 形参包 运算符 ... ) (1)
( ... 运算符 形参包 ) (2)
( 形参包 运算符 ... 运算符 初值 ) (3)
( 初值 运算符 ... 运算符 形参包 ) (4)
例子:
点击查看代码
template<class... args>//可变模板形参
bool all(args... ar) {
return (...&&ar);
}
void test11() {
bool b = all(true, true, true, false);
cout << b << endl;//输出为0
}
二.类模板参数推导
类模板实例化时,可以不必显式指定类型,前提是保证类型可以推导
点击查看代码
template<class T>
class ClassTest2 {
public:
ClassTest2(T, T) {};
};
void test12() {
auto y = new ClassTest2{ 100,200 };
return;
}
三.auto 占位的非类型模板形
例子:
点击查看代码
void func1() {
cout << T << endl;
}
void test13() {
func1<100>();
return;
}
四.编译期constexpr if语
点击查看代码
template<bool ok>constexpr void func2() {
if constexpr (ok == true) {
cout << "ok" << endl;
}
else {
cout << "not ok" << endl;
}
}
void test14() {
func2<true>();
func2<false>();
return;
}

浙公网安备 33010602011771号