C++函数对象-函数包装器-调用空的 std::function 时抛出的异常(std::bad_function_call)

任何定义了函数调用操作符的对象都是函数对象。C++ 支持创建、操作新的函数对象,同时也提供了许多内置的函数对象。


函数包装器

std::function 提供存储任意类型函数对象的支持。

用空的 std::function 时抛出的异常

std::bad_function_call

class bad_function_call;

(C++11 起)

std::bad_function_call 是若函数包装器无目标,则 std::function::operator() 将抛出的异常类型。

成员函数

(构造函数)

构造 bad_function_call 对象
(公开成员函数)

std::bad_function_call::bad_function_call()

bad_function_call() noexcept;

构造新的 std::bad_function_call 实例。

继承图

参数

(无)

继承自 std::exception

成员函数

(析构函数)

[虚]

析构该异常对象
(std::exception 的虚公开成员函数)

what

[虚]

返回解释性字符串
(std::exception 的虚公开成员函数)

调用示例

#include <iostream>
#include <functional>

int main()
{
    std::cout << std::boolalpha;

    std::function<int()> function1 = nullptr;
    std::cout << function1.target_type().name() << std::endl;
    std::cout << typeid(function1).name() << "  function1 bool : "
              << (function1 ? true : false) << std::endl;

    try
    {
        function1();
    }
    catch (const std::bad_function_call& e)
    {
        std::cout << e.what() << std::endl;
    }

    std::function<bool(int)> function2 = [](int num)
    {
        return num % 2 == 1;
    };
    std::cout << function2.target_type().name() << "  function2(1024): "
              << function2(1024) << std::endl;
    std::cout << typeid(function2).name() << "  function2 bool : "
              << (function2 ? true : false) << std::endl;
    std::cout << typeid(function2).name() << "  target_type()  : "
              << (function2.target_type() == typeid(bool(*)(int)) ? true : false) << std::endl;
    std::cout << typeid(function2).name() << "  function2.target<bool(*)(int)>() : "
              << function2.target<bool(*)(int)>() << std::endl;

    return 0;
}

输出

v
St8functionIFivEE  function1 bool : false
bad_function_call
Z4mainEUliE_  function2(1024): false
St8functionIFbiEE  function2 bool : true
St8functionIFbiEE  target_type()  : false
St8functionIFbiEE  function2.target<bool(*)(int)>() : 0

  • 17
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值