繁体   English   中英

c++ 需要带有反向返回类型概念检查的表达式

[英]c++ requires expression with inverse return type concept check

我尝试使用 requires 表达式定义一个概念,该表达式检查类型上是否存在某些成员 function。
我遇到的问题是,必须插入一个概念以进行返回类型检查,而无需任何前面的 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 */
};

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

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

演示

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

尝试这个

#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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM