c++ - C++20 的 'requires' 关键字会减慢你的程序吗?
问题描述
考虑这个类:
class Person
{
std::string name;
std::string last;
int age;
public:
template<typename T1, typename T2>
Person(T1&& name, T2&& last, int age) noexcept
: name(std::forward<T1>(name))
, last(std::forward<T2>(last))
, age(age)
{}
Person(const Person& other) noexcept = default;
Person(Person&& old) noexcept = default;
Person& operator=(const Person& other) noexcept = default;
Person& operator=(Person&& old) noexcept = default;
};
你会用...重写构造函数的模板吗?会更快吗?
template<typename T1, typename T2> requires (
std::is_same_v<std::decay_t<T1>, std::string> &&
std::is_same_v<std::decay_t<T2>, std::string>
)
另一个问题只是原因......我可以制作这些构造函数constexpr
吗?如果是这样,它会更有效吗?
解决方案
C++20 的 'requires' 关键字会减慢你的程序吗?
不,它在评估需求的模板参数上指定了一个常量表达式 - 或者在模板声明中,指定了一个关联的约束。
模板参数(和约束)本质上必须是编译时间常数,并且不会影响编译程序的速度。
推荐阅读
- android-studio - 我在我的 Android Studio 应用程序中添加了一个带有日/夜模式主题的选项菜单,但单击日间模式会关闭应用程序
- python - python:迭代列表或异步生成器
- operating-system - 计算FAT表的大小
- r - NetCDF:仅在 R 中的循环内出现 HDF 错误
- sql - 学习使用 2 个表之间的连接
- php - 当payload突然变为NULL时如何解决Laravel 8中的“payload is invalid”
- mysql - 在 MySQL 中将分号分隔的字符串转换为 JSON 数组
- flutter - Flutter + Firestore 聊天.. Listview 重建所有项目
- android-studio - 如何在 Logcat 中为输出着色或在 Android Studio 中运行?
- node.js - 当有人加载我的 npm 包时,我如何运行 javascript 代码?