简体   繁体   English

如何检查签名的返回类型?

[英]How to check for a signed return-type?

Imagine I have a callable template-parameter "Fn fn".假设我有一个可调用的模板参数“Fn fn”。 Now I want to check that its return-type is a signed scalar.现在我想检查它的返回类型是否是一个带符号的标量。 How can I do that with C++20 concepts?我如何使用 C++20 概念来做到这一点?

To check if it can be called and return something of a category, just call it and examine the expression.要检查是否可以调用它并返回某个类别的内容,只需调用它并检查表达式即可。 That's what concepts are after all, a tool to write regular C++ code into and examine some of its properties.毕竟,这就是概念,一种用于编写常规 C++ 代码并检查其某些属性的工具。

template<typename T>
concept signed_scalar = std::signed_integral<T> || std::floating_point<T>;

template<typename Fn, typename... Args>
concept signed_result = requires(Fn fn, Args... args) {
    { fn(args...) } -> signed_scalar;
};

That's the only generic way given that overloading is always possible in any C++ program, including on a functor's operator() .这是唯一的通用方法,因为在任何 C++ 程序中总是可以重载,包括在仿函数的operator()上。

You can also be fancy and use std::invoke in lieu of the bare function call expression, to handle more "invokable" types.您也可以喜欢并使用std::invoke代替裸 function 调用表达式,以处理更多“可调用”类型。 But you did not give an indication that's a requirement.但是您没有表明这是一项要求。

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

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