构造包装为空或存储任意类型可调用对象具有固定的签名。
function();
function(nullptr_t npc);
function(const function& _Right);
template<class Fx>
function(Fx _Func);
template<class Fx>
function(reference_wrapper<Fx> _Fnref);
template<class Fx, class Alloc>
function(
Fx _Func,
const Alloc& _Ax
);
template<class Fx, class Alloc>
function(
reference_wrapper<Fx> _Fnref,
const Alloc& _Ax
);
参数
_Right
为复制的函数对象。Fx
可调用对象的类型。_Func
为包装的可调用对象。Alloc
分配程序类型。_Ax
分配器。_Fnref
为包装的可调用对象引用。
备注
前两构造函数构造一个 function 对象。 接下来的三构造函数构造一个可调用的对象作为操作数的 function 对象。 前两构造函数分配的分配程序对象_Ax 的存储空间。
示例
// std_tr1__functional__function_function.cpp
// compile with: /EHsc
#include <functional>
#include <iostream>
#include <vector>
int square(int val)
{
return val * val;
}
class multiply_by
{
public:
explicit multiply_by(const int n) : m_n(n) { }
int operator()(const int x) const
{
return m_n * x;
}
private:
int m_n;
};
int main()
{
typedef std::vector< std::function<int (int)> > vf_t;
vf_t v;
v.push_back(square);
v.push_back(std::negate<int>());
v.push_back(multiply_by(3));
for (vf_t::const_iterator i = v.begin(); i != v.end(); ++i)
{
std::cout << (*i)(10) << std::endl;
}
std::function<int (int)> f = v[0];
std::function<int (int)> g;
if (f) {
std::cout << "f is non-empty (correct)." << std::endl;
} else {
std::cout << "f is empty (can't happen)." << std::endl;
}
if (g) {
std::cout << "g is non-empty (can't happen)." << std::endl;
} else {
std::cout << "g is empty (correct)." << std::endl;
}
return 0;
}
要求
标头: <起作用的>
命名空间: std