我们为什么要使用Concept& Constraint [英] Why do we use Concept&Constraint

查看:50
本文介绍了我们为什么要使用Concept& Constraint的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太了解为什么C ++ 20提供了这样的功能.我需要有人指出如何正常使用此功能.这是一个示例:

I don't really understand why C++20 provides such a feature like that. I need someone to point out how to use this feature gracefully. Here is an example:

template<typename T>
concept LessCompareable=requires(const T& lhs, const T& rhs)
{
      {lhs<rhs}->bool;
};

现在,我已经定义了一个概念.然后,我将约束一个函数模板,如下所示:(好吧,我们将其命名为 comp ,实际上就像 std :: min 一样)

Now I've defined a concept. Then I'll constraint a function template like this: (well, let's name it comp, in fact it just like std::min)

template<typename T>
const T& comp(const T& a , const T& b) requires LessCompareable<T>
{return a<b?a:b;}

问题是如果您这样称呼

std::thread a,b;
cout<<comp(a,b);

发生错误

但是如果我们不使用约束,则CE也会发生.

but if we don't use constraint, CE will occur, too.

这让我感到困惑,他们俩都拥有CE,那为什么还要使用约束条件呢?

So that makes me puzzled, both of them have CE, then why I should use constraints?

我认为如果要清除错误消息,可以使用SFINAE.

I think if I want to clean up error messages, I can use SFINAE.

推荐答案

约束的目的是允许您使用内置语言构造为操作指定前提条件.这些前提条件可以由编译器检查,并且可以:

The purpose of constraints is to allow you to specify pre-conditions on operations using built-in language constructs. Those pre-conditions could be checked by the compiler and either:

  1. 您会收到清晰的错误消息.
  2. 在过载解决方案中将不考虑过载(是的,这是执行SFINAE的另一种方法).

很高兴看到错误消息,但是新的#2前提条件检查才是真正的实质.要获得相同的效果,在C ++ 20之前需要做的事情是这样的:

The error messages are nice to have, but the new pre-condition checks for #2 are the real meat of this. What you'd need to do before C++20 to obtain the same effect is something like this:

template<typename T,
         std::enable_if_t<has_less_than_op<T>::value, int> = 0>
const T& comp(const T& a , const T& b) 
{return a<b?a:b;}

它笨拙且繁琐,您需要对SFINAE技术有所了解,才能理解为什么有人会写这样的东西.这是非常专家友好的.模板已经具有这种功能,但这是历史的巧合.概念(精简版)和约束条件使人们能够以更加自然的方式表达同一件事.

It's clunky and cumbersome, and you need to have foreknowledge about SFINAE techniques to understand why someone would ever write something like that. It's extremely expert friendly. Templates already have that power, but that is an historical coincidence. Concepts (lite) and constraints give the ability to express the same thing in a much more natural way.

将以上内容与您的OP或以下内容进行比较:

Compare the above with your OP or this:

template<LessCompareable T>
const T& comp(const T& a , const T& b)
{return a<b?a:b;}

哪种选择更清晰?我会说这不是旧技术.

Which of the alternatives expresses things clearer? Not the old technique, I'd say.

这篇关于我们为什么要使用Concept&amp; Constraint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆