Bon*_*ero 2 c++ function return-type c++-concepts c++20
有一个std::convertible_to<T>概念是检查调用结果是否可以转换为某种类型。
但我想检查函数是否具有确切的返回类型。我怎样才能做到这一点?
您可以编写一个概念,使用来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;
}
Run Code Online (Sandbox Code Playgroud)
(参见现场演示)