【问题标题】:C++20 concept : requires expression and perfect forwardingC++20 概念:需要表达和完美转发
【发布时间】:2020-01-20 18:08:27
【问题描述】:

仅供参考:C++17 std::is_invocable_v 完全符合我的预期。

想象一个概念来检查是否可以使用特定参数类型调用可调用对象:

template <typename Fn, typename... Args>
concept has_request_interface = requires (Fn request, Args&&... args)
{
    { std::invoke(request, std::forward<Args>(args)...) }-> Status;
};

template <typename Fn, typename... Args>
concept has_request_interface = requires (Fn request, Args... args)
{
    { std::invoke(request, args...) }-> Status;
};

在 requires 表达式中使用完美转发有意义吗?

在我看来答案是肯定的,因为请求可调用对象可能期望某些参数的右值。

但是requires (Fn request, Args... args) 是否表现为关于args... 的左值性质的函数声明?

【问题讨论】:

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


    【解决方案1】:

    它的行为将与它看起来完全一样。这就是requires 表达式的意义所在:让这些东西看起来像 C++。所以它会表现得像 C++。

    重要的是你如何使用这个概念。也就是说,当你requires一些基于它的模板时,你应该正确地调用这个概念。例如:

    template<typename Func, typename ...Args
    void constrained(Func func, Args &&...args)
      requires has_request_interface<Func, Args...>
    {
      Status status = func(std::forward<Args>(args)...);
    }
    

    所以是的,如果您想通过概念进行转发,您的概念需要使用&amp;&amp; 和转发。

    【讨论】:

    • 由于您将其编辑回来,decltype(std::forward&lt;Args&gt;(args))... 可以只是 Args...(或 Args&amp;&amp;...,如果您有一个区分这些的概念,而 OP 中的概念则不会)。
    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多