【问题标题】:How to check a function has an exact return-type using Concept?如何使用 Concept 检查函数是否具有准确的返回类型?
【发布时间】:2021-09-22 07:11:29
【问题描述】:

有一个std::convertible_to<T>的概念来检查调用的结果是否可以转换为某种类型。

但我想检查一个函数是否具有精确的返回类型。我该怎么做?

【问题讨论】:

标签: c++ function c++20 return-type c++-concepts


【解决方案1】:

您可以编写一个概念,使用std::same_as 来检查函数的返回类型:

例子:

#include <concepts> // std::same_as

template<typename FuncType, typename RetType>
concept SameReturn = requires(FuncType func) {
    { func() } -> std::same_as<RetType>;
};

template<typename Callable> requires SameReturn<Callable, int>
auto test(Callable func)
{
    return func();
}

int main()
{
    std::cout << test([]() {return 1; });
    // std::cout << test([]() {return "string literals"; }); // error!
    return 0;
} 

(See a Live Demo)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-14
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2019-05-07
    • 2021-06-05
    • 1970-01-01
    相关资源
    最近更新 更多