gpt4 book ai didi

c++ - 约束和概念的定义顺序 c++20

转载 作者:行者123 更新时间:2023-12-05 09:25:52 24 4
gpt4 key购买 nike

概念或约束的正确位置在哪里?

编译以下代码:

void f(int x) { } 

template <typename T>
concept Concept =
requires (T a)
{ f(a); };


template <typename T>
requires Concept<T>
struct A
{ };



int main(){
A<int> a;
}

但是如果我将函数 f(int) 的位置更改为:

template <typename T>
concept Concept =
requires (T a)
{ f(a); };


void f(int x) { } // <-- new position

template <typename T>
requires Concept<T>
struct A
{ };



int main(){
A<int> a;
}

这不能在 gcc 11.3.0 中编译。我收到以下错误:

main.cpp:27:10: error: template constraint failure for ‘template<class T>  requires  Concept<T> struct A’
27 | A<int> a;
| ^
main.cpp:27:10: note: constraints not satisfied
main.cpp: In substitution of ‘template<class T> requires Concept<T> struct A [with T = int]’:
main.cpp:27:10: required from here
main.cpp:12:9: required for the satisfaction of ‘Concept<T>’ [with T = int]
main.cpp:13:5: in requirements with ‘T a’ [with T = int]
main.cpp:14:8: note: the required expression ‘f(a)’ is invalid
14 | { f(a); };

最佳答案

如果函数在模板之后声明,模板调用它的唯一方式是通过ADL。 . int是内置类型,因此不会发生 ADL。

如果参数是例如类类型,在与 f() 相同的命名空间中定义, 它会起作用。

Clang 解释说:

...
<source>:5:7: note: because 'f(a)' would be invalid: call to function 'f' that is neither visible in the template definition nor found by argument-dependent lookup

关于c++ - 约束和概念的定义顺序 c++20,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74914589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com