c++ - 这是对 C++20 概念的正确使用吗?
问题描述
我有一个简单的Vec3<T>
类,我想使用 C++20 概念(带有 -std=c++20 的 Clang 10.0.0)对其进行更新。新版本看起来像这样:
template <typename T> concept Arithmetic = std::is_arithmetic_v<T>;
template <typename T> concept FloatingPoint = std::is_floating_point_v<T>;
template <Arithmetic T> struct Vec3 {
T x, y, z;
/* operator overloading, etc.. */
void normalize() requires FloatingPoint<T>;
};
这是对 C++20 概念的正确使用吗?核心指南 T11建议尽可能使用标准概念,但我在名为 requirements 的 C++ 列表和头<concepts>
文件中都找不到我想要的概念。这是因为我的概念太具体,根本不应该是概念吗?
我的原始代码混合使用static_assert
SFINAE 来获得最终结果。
解决方案
我们已经有了一个浮点类型的概念,它是std::floating_point
. 缺少std::arithmetic
似乎是一个疏忽,并且已经注意到,请参阅N4844,第 50 页:
美国 193 . C++20 缺少算术类型的概念。这种遗漏令人惊讶,因为这是一个相当常见的用例。例如,假设我想编写一个对数字求平方的函数。在 C++20 之前,我可能会写:
template <typename T> auto square(T x) {return x * x;}
在 C++20 中,能够这样写似乎很自然:
auto square(std::arithmetic auto x) {return x * x;}
但是,缺少这样的标准库概念!相反,我们必须写得更冗长:
template <typename T> requires std::is_arithmetic_v<T> auto square(T x) {return x * x;}
提议的变化:
template<class T> concept arithmetic = is_arithmetic_v<T>;
但是std::arithmetic
应该如何定义的问题并不像看起来那么容易。看到这个问题。正如巴里在评论中指出的那样,提议的更改被拒绝了。
推荐阅读
- javascript - 试图在声音停止后获得一个按钮来刷新页面。按下按钮时声音开始
- geom-bar - 如何订购离散的 x 轴?
- android - IF 条件为真,但程序执行 else
- php - 尽管在本地服务器上工作,但在托管服务器上上传 Laravel 图像不起作用
- jquery - 如何强制在 laravel 中对 AJAX 请求返回 HTTP 响应
- c - 等距瓷砖拾取/选择算法
- javascript - 我可以暂停函数的执行,直到在节点中接收到某个值?
- vb.net - 如何让我的应用程序在启动时检查更新然后下载?
- c# - Url.Page 创建错误的 url
- javascript - 如何从 Javascript 中的查询 Firebase 中获取密钥