![](/img/trans.png)
[英]How to use C++20 concepts to check some constraints in the template itself
[英]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
例如, short
是Integral
,但不太可能满足Integral4
。
但是f
有权在它提供的模板上使用short
,因为这是它的签名说它可以做的事情。 由于提供的S3
仅允许f
的签名允许它使用的类型的子集,因此您会收到编译错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.