C ++ 20概念:需要表达和完美的转发

问题描述 投票:1回答:1

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

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

在require表达式中使用完美转发是否有意义?

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

但是requires (Fn request, Args... args)是否充当有关args...左值性质的函数声明?

c++ c++20 c++-concepts
1个回答
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)...); }
是的,如果您想通过概念进行转发才能起作用,则您的概念需要使用&&和转发。
© www.soinside.com 2019 - 2024. All rights reserved.