首页 > 解决方案 > 这是对 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_assertSFINAE 来获得最终结果。

标签: c++c++20c++-concepts

解决方案


我们已经有了一个浮点类型的概念,它是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应该如何定义的问题并不像看起来那么容易。看到这个问题。正如巴里在评论中指出的那样,提议的更改被拒绝了


推荐阅读