【问题标题】:Disabling function that uses concept constrain if concept is not met如果不满足概念,则禁用使用概念约束的功能
【发布时间】:2023-01-11 04:04:58
【问题描述】:

如何编译以下代码?

我正在尝试检查 BigStruct 是否存在于某个类型中,如果存在,则启用 f

#include <type_traits>
struct A {
    using BigStruct = int;
}; 

struct C {
};

template <typename T>
struct B {
    void f(typename T::BigStruct t) requires requires {T::BigStruct;} {}
};

int main() {
  B<A> b1;
  B<C> b2;
}

我得到的错误:

<source>:11:24: error: no type named 'BigStruct' in 'C'
    void f(typename T::BigStruct t) requires requires {T::BigStruct;} {}
           ~~~~~~~~~~~~^~~~~~~~~
<source>:16:8: note: in instantiation of template class 'B<C>' requested here
  B<C> b2;
       ^
1 error generated.
ASM generation compiler returned: 1
<source>:11:24: error: no type named 'BigStruct' in 'C'
    void f(typename T::BigStruct t) requires requires {T::BigStruct;} {}
           ~~~~~~~~~~~~^~~~~~~~~
<source>:16:8: note: in instantiation of template class 'B<C>' requested here
  B<C> b2;
       ^
1 error generated.
Execution build compiler returned: 1

Here's a godbolt link for x86-64 clang trunk

【问题讨论】:

  • 你得到什么错误?
  • B 是类模板是故意的吗?或者您可能只是想让f 成为一个函数模板?
  • @tadman 不编译,“‘C’中没有名为‘BigStruct’的类型”
  • @463035818_is_not_a_number B 是一个类模板是故意的。
  • 如今,错误消息包含了如此多的信息。使用它们。在问题中包含完整的错误消息。

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


【解决方案1】:

非模板函数的概念检查发生在生成函数签名之后。这意味着参数列表必须存在。因此,它必须在句法上有效。

在这种情况下,如果您不想限制整个类,除了 making the function itself a template 的旧 C++20 之前的策略之外,您无能为力:

template<typename U = T>
  requires requires {typename U::BigStruct;} 
void f(typename U::BigStruct t) {}

【讨论】:

  • 需求有好处吗?我问是因为它似乎没有godbolt.org/z/3nMne65Ee也有同样的效果
  • @463035818_is_not_a_number:它更清楚地说明了要求是什么。 SFINAE 有点像 hack。
猜你喜欢
  • 2020-11-30
  • 2020-01-27
  • 2022-12-13
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
相关资源
最近更新 更多