版权所有 © 2011, 2012 Lorenzo Caminiti
根据 Boost Software License, Version 1.0 分发(请参阅附带的 LICENSE_1_0.txt 文件或在 https://boost.ac.cn/LICENSE_1_0.txt 复制)
目录
该库允许将不同的函数重载成一个函数对象。
考虑以下具有不同签名的函数
const std::string& identity_s(const std::string& x) // Function (as pointer). { return x; } int identity_i_impl(int x) { return x; } int (&identity_i)(int) = identity_i_impl; // Function reference. double identity_d_impl(double x) { return x; } boost::function<double (double)> identity_d = identity_d_impl; // Functor.
与其使用它们各自的名称来调用它们(此处 BOOST_TEST
等同于 assert
): [1]
BOOST_TEST(identity_s("abc") == "abc"); BOOST_TEST(identity_i(123) == 123); BOOST_TEST(identity_d(1.23) == 1.23);
可以使用此库创建一个名为 identity
的单一 重载 函数对象(或 仿函数),该函数对象聚合了对特定函数的调用(另请参见 functor.cpp
和 identity.hpp
)。
boost::overloaded_function< const std::string& (const std::string&) , int (int) , double (double) > identity(identity_s, identity_i, identity_d); // All calls via single `identity` function. BOOST_TEST(identity("abc") == "abc"); BOOST_TEST(identity(123) == 123); BOOST_TEST(identity(1.23) == 1.23);
请注意,函数是如何通过单个重载函数对象 identity
调用,而不是使用它们各自的名称 identity_s
、identity_i
和 identity_d
。
[1] 在此文档中展示的大多数示例中,Boost.Core/LightweightTest(boost/core/lightweight_test.hpp
)宏 BOOST_TEST
用于检查正确性条件(概念上类似于 assert
)。被检查条件的失败不会中止程序的执行,而是会使 boost::report_errors
返回一个非零的程序退出码。使用 Boost.Core/LightweightTest 可以将示例添加到库回归测试中,以确保它们始终能正确编译和运行。