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

标签 c++ c++20 c++-concepts

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

编译以下代码:

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/

相关文章:

c++ - Hadoop C++,运行wordcount示例时出错

c++ - 为什么我可以在 constexpr 函数中修改 const_cast-ed 对象?

C++ 概念 Same 和 Assignable

c++ - clang 10 C++ 20概念如何为类方法指定复合要求?

C++ I/O 流问题 : program asks for input twice or work incorrectly

C++/WinRT : Can I await a single IAsyncAction handle from multiple coroutine calls?

C++ ofstream - 只有 1 个字符串被写入文件,之前的字符串被覆盖,为什么?

c++20 执行策略类型

c++ - STL或范围算法有效地找到满足谓词的n个连续元素

c++ - 如何编写结构化绑定(bind)的概念?