确定与 std::function<R(T1,T2)兼容的函数类型集的规则>?

Rules for determining the set of function type compatible with std::function<R(T1,T2)>?

本文关键字:函数 gt 类型 规则 T1 function std lt T2      更新时间:2023-10-16

假设我有这个

std::function<int(int,int)> fs;

那么我如何确定fs可以初始化的函数集(或函数对象)?

以下哪些是允许的,哪些是不允许的:

std::function<int(int,int)> fs = [](int, int) { return int(10); };
std::function<int(int,int)> fs = [](char, char) { return char(10); };
std::function<int(int,int)> fs = [](int, short) { return int(10); };
std::function<int(int,int)> fs = [](double, int) { return float(10); };
std::function<int(int,int)> fs = [](int, wchar_t) { return wchar_t(10); };
std::function<int(int,int)> fs = [](const char*, int){ return "string"; };
std::function<int(int,int)> fs = [](const char*, int){ return 10; };
std::function<int(int,int)> fs = [](const char*, int){ return std::string(); };

当然,我可以编译,看看哪一个可以编译,哪一个不能。但这并不能帮助我理解参数类型和返回类型的变化。我能在多大程度上为它们使用不同的类型?

换句话说,如果我给出了一个函数(或函数对象),我如何在编译时确定它是否与std::function<int(int,int)>兼容?我懂的不多,但我不够自信。

所以请帮助我理解和制定确定与std::function<R(T1,T2)>兼容的功能类型集的规则?元编程可以帮助我在这里通知用户,生成漂亮的错误消息,如果他们使用不兼容的功能?

顺便说一下,第一组似乎是兼容的:http://ideone.com/hJpG3

对象(函数指针或函子)必须具有给定参数类型的可调用性,即fun( declval< Types >() ... )是格式良好的,可以隐式地转换为R

参见c++ 11§20.8.2;它给出了指向成员的指针的各种特殊情况,等等。§20.8.11.2/2和20.8.11.2.1/7将此与std::function构造函数联系起来。

没有预先打包的元编程解决方案。为了解决这个问题,我列出了以下几个特点。这些特征只是实现了Potatoswatter回答中提到的部分。代码注释甚至列举了引用部分中的项目符号。

template <class _F, class ..._Args> struct __invokable;
template <class _F, class ..._Args> struct __invoke_of;
http://llvm.org/svn/llvm-project/libcxx/trunk/include/type_traits

我使用这些来创建std::function的私有"成员trait":

template <class _F, bool = __invokable<_F&, _ArgTypes...>::value>
    struct __callable;
http://llvm.org/svn/llvm-project/libcxx/trunk/include/functional

我想到这些可能是很好的tr2材料(没有开头的下划线)。如果你同意,也许你应该让你的国家机构代表知道。

如果你想使用这些特性,代码是开源的。但是,如果您尊重开源许可证,在每个文件中包含版权信息,我将不胜感激。