C++20 概念 : requires expression and perfect forwarding

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

仅供引用: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... 的左值性质的函数声明?

最佳答案

它的行为将与它看起来的完全一样。这就是 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)...);
}

所以是的,如果你想通过概念转发工作,你的概念需要使用 &&和转发。

关于C++20 概念 : requires expression and perfect forwarding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59828801/

相关文章:

c++ - 指向不同类型的指针

C++20 使用概念来强制类上的接口(interface)

c++ - Windows 中 boost::serialization 的未知异常

c++ - 如何方便地初始化函数指针数组?

c++ - 类似于 `declval` 的概念

c++ - 为什么Boost.Concept通过空指针调用析构函数?

c++ - 如何将概念用作模板参数?

c++ - 如何处理仅适用于 -fconcepts 的参数声明中的 "warning: use of ‘auto’”

c++ - 链接到静态QT,如何找出正确的链接顺序?

c++ - 重击 : warning: command substitution: ignored null byte in input