Yang Liu
Yang Liu

Reputation: 173

assert a function pointer compatible with std::function

What is the best practice to assert a callable is compatible with a std::function. Which tells whether the callable can be passed as argument where a relative std::function type is needed.

Examples:

int foo(int a) { return a; }
auto bar = [](int a)->int { return a; }
char baz(char a) { return a; }

compatible(foo, std::function<int(int)>) == true
compatible(bar, std::function<int(int)>) == true
compatible(baz, std::function<int(int)>) == true

Upvotes: 1

Views: 352

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477100

For your updated question, maybe the following would work:

#include <functional>
#include <type_traits>

template <typename T, typename F>
constexpr bool compatible(F const & f)
{
    return std::is_constructible<std::function<T>, F>::value;
}

Usage:

std::cout << compatible<int(int)>(foo) << std::endl;
std::cout << compatible<int(int)>(bar) << std::endl;
std::cout << compatible<int(int)>(baz) << std::endl;

Upvotes: 2

Related Questions