简体   繁体   English

这是对 C++20 概念的正确使用吗?

[英]Is this a proper use of C++20 concepts?

I have a simple Vec3<T> class, and I would like to update it using C++20 concepts (Clang 10.0.0 with -std=c++20).我有一个简单的Vec3<T> class,我想使用 C++20 概念(带有 -std=c++20 的 Clang 10.0.0)对其进行更新。 The new version looks something like this:新版本看起来像这样:

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>;
};

Is that a proper use of C++20 concepts?这是对 C++20 概念的正确使用吗? The 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 , nor in the <concepts> header file. 核心指南 T11建议尽可能使用标准概念,但我在C++ 命名要求列表和<concepts> header 文件中找不到我想要的。 Is this because my concepts are too specific, and shouldn't be concepts at all in the first place?这是因为我的概念太具体,根本不应该是概念吗?

My original code uses a mix of static_assert and SFINAE to get to the end result.我的原始代码混合使用了static_assert和 SFINAE 来获得最终结果。

We already have a concept for a floating point type, it isstd::floating_point .我们已经有了一个浮点类型的概念,它是std::floating_point The absence of std::arithmetic seems to be an oversight and has already been noted, see N4844 , page 50:缺少std::arithmetic似乎是一个疏忽,并且已经注意到,请参阅N4844 ,第 50 页:

US 193 .美国 193 . C++20 lacks a concept for arithmetic types. C++20 缺少算术类型的概念。 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.例如,假设我希望编写一个对数字进行平方的 function。 Pre C++20, I might write:在 C++20 之前,我可能会写:

 template <typename T> auto square(T x) {return x * x;}

In C++20, it would seem natural to be able to write:在 C++20 中,能够这样写似乎很自然:

 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>;

But the question of how std::arithmetic should be defined is not that easy as it might seem to be.但是如何定义std::arithmetic的问题并不像看起来那么容易。 See this question .看到这个问题 As Barry noted in the comment, that proposed change was rejected .正如巴里在评论中指出的那样,提议的更改被拒绝了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM