C++ 断言与std::function兼容的函数指针

C++ 断言与std::function兼容的函数指针,c++,std-function,C++,Std Function,断言可调用函数与std::function兼容的最佳实践是什么。这说明在需要相对std::function类型时,是否可以将可调用函数作为参数传递 示例: 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(ba

断言可调用函数与
std::function
兼容的最佳实践是什么。这说明在需要相对
std::function
类型时,是否可以将可调用函数作为参数传递

示例:

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
intfoo(inta){返回a;}
自动栏=[](int a)->int{return a;}
charbaz(chara){返回a;}
兼容(foo,std::function)==true
兼容(条,标准::函数)=真
兼容(baz,std::function)==true

对于您更新的问题,也许以下方法可行:

#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;
}
#包括
#包括
模板
constexpr布尔兼容(F const&F)
{
返回std::is_constructible::value;
}
用法:

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

std::cout您所问的问题还不清楚,可能是一个函数的签名,它将接受这个可调用函数,这将有帮助(?)很简单,这应该可以通过
std::is_function
std::is_same
实现。第一个和第三个示例的左参数是类型,第二个示例的左参数是值。这是没有意义的。否则,
是可构造的
应该是这个检查有效的一个特征。@KerrekSB,你应该做出回答,
是相同的
是一个太强的检查…@Nim:我不太理解这个问题,特别是lambda部分:-(