Tou*_*dou 9 c++ c++-concepts 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>;
};
Run Code Online (Sandbox Code Playgroud)
这是对 C++20 概念的正确使用吗?该核心准则T11推荐使用标准的概念,尽可能的,但我找不到我在想的那些C ++的命名要求列表,也没有在<concepts>头文件。这是因为我的概念太具体了,一开始就不应该是概念吗?
我的原始代码使用static_assert和 SFINAE的混合来获得最终结果。
我们已经有了一个浮点类型的概念,它是std::floating_point. 缺少std::arithmetic似乎是一个疏忽,并且已经注意到,参见N4844,第 50 页:
美国 193。C++20 缺乏算术类型的概念。这种遗漏令人惊讶,因为这是一个相当常见的用例。例如,假设我想编写一个对数字求平方的函数。在 C++20 之前,我可能会写:
Run Code Online (Sandbox Code Playgroud)template <typename T> auto square(T x) {return x * x;}在 C++20 中,能够这样写似乎很自然:
Run Code Online (Sandbox Code Playgroud)auto square(std::arithmetic auto x) {return x * x;}但是,缺少这样一个标准库概念!相反,我们必须写得更冗长:
Run Code Online (Sandbox Code Playgroud)template <typename T> requires std::is_arithmetic_v<T> auto square(T x) {return x * x;}提议的改变:
Run Code Online (Sandbox Code Playgroud)template<class T> concept arithmetic = is_arithmetic_v<T>;
但是std::arithmetic应该如何定义的问题并不像看起来那么容易。看到这个问题。正如巴里在评论中指出的那样,提议的更改被拒绝了。
| 归档时间: |
|
| 查看次数: |
389 次 |
| 最近记录: |