【问题标题】:c++ requires expression with inverse return type concept checkc ++需要具有反向返回类型概念检查的表达式
【发布时间】:2021-05-27 09:41:08
【问题描述】:

我尝试使用 requires 表达式定义一个概念,该表达式检查该类型上是否存在某些成员函数。
我遇到的问题是,必须插入一个概念以进行返回类型检查,而无需任何前面的 bool 操作,如“not”。如果需要,这迫使我还要编写逆的概念,这不是很方便。
有什么我遗漏的东西或其他好方法吗?

简单示例:

template <typename T>
concept IsReference = std::is_reference_v<T>;

template <typename T>
concept HasSomeFunction = requires (T t) {
    {t.func()} -> IsReference; /* this is ok */
    {t.anotherFunc()} -> (not IsReference); /* this is not ok */
};

【问题讨论】:

  • 所以……您可以使用 voidvolatile void*wchar_t(*(*(*)[])(...))[1]float std::vector&lt;bool&gt;::*std::in_place_type_t&lt;void() volatile &amp;&amp;&gt;std::pair&lt;int&amp;,char&amp;&gt;std::reference_wrapper&lt;int&gt;,但不能使用 const int&amp;? “除此之外的任何东西”的语法似乎都有问题。

标签: c++ templates require c++-concepts


【解决方案1】:

这是适用于最新 gcc 和 clang 的语法。

template <typename T>
concept HasSomeFunction = requires (T t) {
    {t.func()} -> IsReference; /* this is ok */
    requires !IsReference<decltype(t.anotherFunc())>;
};

Demo

阅读起来有点困难。也许对概念有更多经验的人可以提供更好的解决方案。

【讨论】:

  • 据我了解 - 这正是编译器对正常返回类型检查所做的转换 - 对我来说,不清楚为什么较短的语法不允许逆向
  • 是的,它也适用于较短的版本似乎是合理的。我不知道为什么不允许这样做。
  • @Lessi - 为什么正好相反?为什么不是任意的布尔表达式?该标准通常会尽可能避免语法中的特殊情况。它不会允许 just 反过来。不仅如此,还有一罐蠕虫。
  • @StoryTeller-UnslanderMonica 你是对的 - 我对我的具体例子很紧张 - 连词和析取也应该是可能的。
  • @Lessi - 因为条件的结合一个概念。
【解决方案2】:

试试这个

#include <memory>
#include <cassert>

struct B {};
struct D : B {};

template <typename T>
concept IsReference = std::is_reference_v<T>;
template <typename T>
concept NotIsReference = !std::is_reference_v<T>;

template <typename T>
concept HasSomeFunction = requires (T t) {
    {t.func()} -> IsReference; /* this is ok */
    {t.anotherFunc()} -> NotIsReference; /* this is not ok */
};


int main() {
    std::shared_ptr<B> b = std::make_shared<D>();
    auto d = static_pointer_cast<D>(b);
    assert(d);
}

【讨论】:

  • 我认为 OP 是在问如何避免写NotIsReference
  • @463035818_is_not_a_number 准确
  • btw cmets 是骗子。 /* this is not ok */,不行吗?
猜你喜欢
  • 1970-01-01
  • 2021-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-28
  • 2021-05-18
  • 2020-06-11
相关资源
最近更新 更多