How to check a function has an exact return-type using Concept?

Viewed 315

There's a std::convertible_to<T> concept to check whether a result of a call can be converted to a certain type.

But I want to check if a function has an exact return-type. How can I do that?

1 Answers

You can write a concept which uses the std::same_as to check the return type of the function:

Example:

#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)

Related