关于约束和概念 [英] About constraints and concepts

查看:98
本文介绍了关于约束和概念的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不明白为什么C ++ 20提供这样的功能。我认为这是冗余,是的,我确定我错了,但是我需要有人指出我为什么错以及如何正常使用此功能。
这是一个示例:

I don't really understand why C++20 provide such a feature like that. I think it's redundant, yes, I'm sure I am wrong, but I need someone to point out why I am wrong and 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.

这篇关于关于约束和概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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