确定与 std::function<R(T1,T2)兼容的函数类型集的规则>?
Rules for determining the set of function type compatible with std::function<R(T1,T2)>?
假设我有这个
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材料(没有开头的下划线)。如果你同意,也许你应该让你的国家机构代表知道。
如果你想使用这些特性,代码是开源的。但是,如果您尊重开源许可证,在每个文件中包含版权信息,我将不胜感激。
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 是否需要使用 - &gt;运算符在C 中调用成员函数时