【发布时间】:2021-09-22 07:11:29
【问题描述】:
有一个std::convertible_to<T>的概念来检查调用的结果是否可以转换为某种类型。
但我想检查一个函数是否具有精确的返回类型。我该怎么做?
【问题讨论】:
-
std::same_as适合你吗?
标签: c++ function c++20 return-type c++-concepts
有一个std::convertible_to<T>的概念来检查调用的结果是否可以转换为某种类型。
但我想检查一个函数是否具有精确的返回类型。我该怎么做?
【问题讨论】:
std::same_as 适合你吗?
标签: c++ function c++20 return-type c++-concepts
您可以编写一个概念,使用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;
}
【讨论】: