Home C&C++函数库 c++ 语法 程序源码 Linux C库

std::

function::target

公共成员函数  <functional>

template <class TargetType>       TargetType* target() noexcept;
template <class TargetType> const TargetType* target() const noexcept;

获取指向目标的指针
返回一个指向存储在function对象中的可调用对象的指针。

因为function是一个多态包装器类,所以它不知道目标可调用对象的静态类型,因此必须显式指定模板形参TargetType。

TargetType应该匹配目标类型,所以typeid(TargetType)==target_type()。否则,函数总是返回空指针。

☲  参数


none

☉  返回值



如果typeid(TargetType)与成员target_type返回的值相等,则返回指向目标可调用对象的指针。否则为空指针。

☣  示例



// function::target example
#include <iostream>     // std::cout, std::boolalpha
#include <functional>   // std::function, std::plus, std::minus

int my_plus (int a, int b) {return a+b;}
int my_minus (int a, int b) {return a-b;}

int main () {
  std::function<int(int,int)> foo = my_plus;
  std::function<int(int,int)> bar = std::plus<int>();

  // calling using functional form:
  std::cout << foo(100,20) << '\n';
  std::cout << bar(100,20) << '\n';

  // calling by invoking target:
  std::cout << (*foo.target<int(*)(int,int)>())(100,20) << '\n';
  std::cout << (*bar.target<std::plus<int>>())(100,20) << '\n';

  // changing target directly:
  *foo.target<int(*)(int,int)>() = &my_minus;
  std::cout << foo(100,20) << '\n';

  return 0;
}

输出:
120
120
120
120
80

⇄ 数据竞争



同时访问对象及其target。
返回的指针可用于访问或修改目标可调用对象。

☂ 异常安全性



无抛出保证:该成员函数从不抛出异常。

🍄  另请参阅



function::target_type 目标内部类型(公共成员函数)
function::operator() 调用目标对象(公共成员函数)

联系我们 免责声明 关于CandCplus 网站地图