繁体   English   中英

c++20 概念的约束

[英]constraints with c++20 concepts

我正在尝试理解 C++20 概念,尤其是此处的示例。 如果我们使用比允许的更严格的概念来模板化f ,为什么会出现错误? 换句话说, Integral4不也满足Integral概念吗?

#include <type_traits>
#include <concepts>

template<typename T>
concept Integral = std::integral<T>;

template<typename T>
concept Integral4 = Integral<T> && sizeof(T) == 4;

template<template<Integral T1> typename T>
void f(){
}

template<typename T>
struct S1{};

template<Integral T>
struct S2{};

template<Integral4 T>
struct S3{};

void test(){
    f<S1>();    // OK
    f<S2>();    // OK
    // error, S3 is constrained by Integral4 which is more constrained than
    // f()'s Integral
    f<S3>();
}

错误

<source>: In function 'void test()':
<source>:28:10: error: no matching function for call to 'f<template<class T>  requires  Integral4<T> struct S3>()'
   28 |     f<S3>();
      |     ~~~~~^~
<source>:11:6: note: candidate: 'template<template<class T1> class requires  Integral<T1> T> void f()'
   11 | void f(){
      |      ^
<source>:11:6: note:   template argument deduction/substitution failed:
<source>:28:10: error: constraint mismatch at argument 1 in template parameter list for 'template<template<class T1> class requires  Integral<T1> T> void f()'
   28 |     f<S3>();
      |     ~~~~~^~
<source>:28:10: note:   expected 'template<class T1> class requires  Integral<T1> T' but got 'template<class T>  requires  Integral4<T> struct S3'
Compiler returned: 1

f采用受Integral约束的模板模板参数。 这意味着f可以在此模板上使用满足Integral的任何类型T

例如, short

S3是受Integral4约束的类型,它包含Integral 这意味着,尽管满足Integral的任何类型U也将满足Integral4 ,但反之则不成立。 有一些类型T满足Integral不满足Integral4

例如, shortIntegral ,但不太可能满足Integral4

但是f有权在它提供的模板上使用short ,因为这是它的签名说它可以做的事情。 由于提供的S3仅允许f的签名允许它使用的类型的子集,因此您会收到编译错误。

暂无
暂无

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

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