三、字面量
用户定义字面量是对字面量运算符""的重载,双引号后必须以_开头进行命名,重载时函数传入相应的参数类型,如字符串需传入字符串首地址及长度
void operator""_t(const char *str, size_t size)
{cout << str << endl;
}int main()
{cout << "---begin---" << endl;"hello world"_t;cout << "---end---" << endl;return 0;
}
输出结果:
---begin---
hello world
---end---
标准库中的字面量后可能不加_
int main()
{cout << "---begin---" << endl;using namespace literals;cout << "hello world"s << endl;cout << "---end---" << endl;return 0;
}
输出结果:
---begin---
hello world
---end---
*同样,我们还可以对数字类型进行定义
size_t operator""_i(size_t n)
{return n + 1;
}int main()
{cout << "---begin---" << endl;cout << 5_i << endl;cout << "---end---" << endl;return 0;
}
输出结果:
---begin---
6
---end---
但是,字面量运算符仅允许包括const char*, size_t, long double, unsigned long long int, char等在内的形参列表,而不包含常用的int, double等类型。
四、noexcept关键字
异常说明符noexcept既可以用作说明符,也可以用作运算符
当函数进行noexcept运算时,默认返回false,当函数被noexcept修饰时返回值为true
作为说明符时,也可以通过noexcept(表达式)的方式进行指定
void func1()
{cout << "func1" << endl;
}void func2() noexcept
{cout << "func2" << endl;
}int main()
{cout << "---begin---" << endl;cout << noexcept(func1()) << endl;cout << noexcept(func2()) << endl;cout << "---end---" << endl;return 0;
}
输出结果:
---begin---
0
1
---end---
不能仅通过异常说明的不同实现函数重载
void func()
{cout << "func" << endl;
}void func() noexcept
{cout << "func" << endl;
}
// error: redefinition of 'void func()'
C++17起,noexcept会作为函数的一部分,指向不会抛出异常的函数指针可以隐式转换到可能会抛出异常的函数指针,反之则不行
void func1()
{cout << "func1" << endl;
}void func2() noexcept
{cout << "func2" << endl;
}int main()
{cout << "---begin---" << endl;// void (*ptr1)() noexcept = func1; /*error*/void (*ptr)() = func2;cout << "---end---" << endl;return 0;
}
作为运算符时,noexcept与typeid,sizeof,decltype,requires类似,其操作数都是不求值表达式,这些运算符都只会查询操作数的编译期性质
int main()
{cout << "---begin---" << endl;int i = 0;cout << noexcept(i++) << endl;cout << i << endl;cout << "---end---" << endl;return 0;
}
输出结果:
---begin---
1
0
---end---