这是对 C++20 概念的正确使用吗?
Is this a proper use of C++20 concepts?
我有一个简单的 Vec3<T>
class,我想使用 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 概念的正确使用吗? core guideline T11 recommends using standard concepts as much as possible, but I couldn't find the ones I wanted in the list of C++ named requirements,也不在 <concepts>
头文件中。是不是我的概念太具体了,根本不应该是概念?
我的原始代码混合使用 static_assert
和 SFINAE 来获得最终结果。
我们已经有了浮点类型的概念,它是 std::floating_point
. The absence of std::arithmetic
seems to be an oversight and has already been noted, see N4844,第 50 页:
US 193. C++20 lacks a concept for arithmetic types. This omission is surprising, as this is a fairly common use case. For example, suppose I wish to write a function that squares a number. Pre C++20, I might write:
template <typename T>
auto square(T x) {return x * x;}
In C++20, it would seem natural to be able to write:
auto square(std::arithmetic auto x) {return x * x;}
However, such a standard library concept is missing! Instead, we must write the more verbose:
template <typename T> requires std::is_arithmetic_v<T>
auto square(T x) {return x * x;}
Proposed change:
template<class T>
concept arithmetic = is_arithmetic_v<T>;
但是 std::arithmetic
应该如何定义的问题并不像看起来那么容易。参见 . As Barry noted in the comment, that proposed change was rejected。
我有一个简单的 Vec3<T>
class,我想使用 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 概念的正确使用吗? core guideline T11 recommends using standard concepts as much as possible, but I couldn't find the ones I wanted in the list of C++ named requirements,也不在 <concepts>
头文件中。是不是我的概念太具体了,根本不应该是概念?
我的原始代码混合使用 static_assert
和 SFINAE 来获得最终结果。
我们已经有了浮点类型的概念,它是 std::floating_point
. The absence of std::arithmetic
seems to be an oversight and has already been noted, see N4844,第 50 页:
US 193. C++20 lacks a concept for arithmetic types. This omission is surprising, as this is a fairly common use case. For example, suppose I wish to write a function that squares a number. Pre C++20, I might write:
template <typename T> auto square(T x) {return x * x;}
In C++20, it would seem natural to be able to write:
auto square(std::arithmetic auto x) {return x * x;}
However, such a standard library concept is missing! Instead, we must write the more verbose:
template <typename T> requires std::is_arithmetic_v<T> auto square(T x) {return x * x;}
Proposed change:
template<class T> concept arithmetic = is_arithmetic_v<T>;
但是 std::arithmetic
应该如何定义的问题并不像看起来那么容易。参见