日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

c++中的bind使用方法_C 語(yǔ)言

作者:xutopia ? 更新時(shí)間: 2022-03-24 編程語(yǔ)言

除了容器有適配器之外,其實(shí)函數(shù)也提供了適配器,適配器的特點(diǎn)就是將一個(gè)類型改裝成為擁有子集功能的新的類型。其中函數(shù)的適配器典型的就是通過(guò)std::bind來(lái)實(shí)現(xiàn)。

std::bind函數(shù)定義在頭文件functional中,是一個(gè)函數(shù)模板,它就像一個(gè)函數(shù)適配器,接受一個(gè)可調(diào)用對(duì)象(callable object),生成一個(gè)新的可調(diào)用對(duì)象來(lái)“適應(yīng)”原對(duì)象的參數(shù)列表。一般而言,我們用它可以把一個(gè)原本接收N個(gè)參數(shù)的函數(shù)fn,通過(guò)綁定一些參數(shù),返回一個(gè)接收M個(gè)(M可以大于N,但這么做沒(méi)什么意義)參數(shù)的新函數(shù)。同時(shí),使用std::bind函數(shù)還可以實(shí)現(xiàn)參數(shù)順序調(diào)整等操作。

可調(diào)用 (Callable) 中描述,調(diào)用指向非靜態(tài)成員函數(shù)指針或指向非靜態(tài)數(shù)據(jù)成員指針時(shí),首參數(shù)必須是引用或指針(可以包含智能指針,如 std::shared_ptrstd::unique_ptr),指向?qū)⒃L問(wèn)其成員的對(duì)象。

官方示例

#include <random>
#include <iostream>
#include <memory>
#include <functional>
 
void f(int n1, int n2, int n3, const int& n4, int n5)
{
    std::cout << n1 << ' ' << n2 << ' ' << n3 << ' ' << n4 << ' ' << n5 << '\n';
}
 
int g(int n1)
{
    return n1;
}
 
struct Foo {
    void print_sum(int n1, int n2)
    {
        std::cout << n1+n2 << '\n';
    }
    int data = 10;
};
 
int main()
{
    using namespace std::placeholders;  // 對(duì)于 _1, _2, _3...
 
    // 演示參數(shù)重排序和按引用傳遞
    int n = 7;
    // ( _1 與 _2 來(lái)自 std::placeholders ,并表示將來(lái)會(huì)傳遞給 f1 的參數(shù))
    auto f1 = std::bind(f, _2, 42, _1, std::cref(n), n);
    n = 10;
    f1(1, 2, 1001); // 1 為 _1 所綁定, 2 為 _2 所綁定,不使用 1001
                    // 進(jìn)行到 f(2, 42, 1, n, 7) 的調(diào)用
 
    // 嵌套 bind 子表達(dá)式共享占位符
    auto f2 = std::bind(f, _3, std::bind(g, _3), _3, 4, 5);
    f2(10, 11, 12); // 進(jìn)行到 f(12, g(12), 12, 4, 5); 的調(diào)用
 
    // 常見(jiàn)使用情況:以分布綁定 RNG
    std::default_random_engine e;
    std::uniform_int_distribution<> d(0, 10);
    std::function<int()> rnd = std::bind(d, e); // e 的一個(gè)副本存儲(chǔ)于 rnd
    for(int n=0; n<10; ++n)
        std::cout << rnd() << ' ';
    std::cout << '\n';
 
    // 綁定指向成員函數(shù)指針
    Foo foo;
    auto f3 = std::bind(&Foo::print_sum, &foo, 95, _1);
    f3(5);
 
    // 綁定指向數(shù)據(jù)成員指針
    auto f4 = std::bind(&Foo::data, _1);
    std::cout << f4(foo) << '\n';
 
    // 智能指針亦能用于調(diào)用被引用對(duì)象的成員
    std::cout << f4(std::make_shared<Foo>(foo)) << '\n'
              << f4(std::make_unique<Foo>(foo)) << '\n';
}

輸出:

2 42 1 10 7
12 12 12 4 5
1 5 0 2 0 8 2 2 10 8
100
10
10
10

原文鏈接:https://www.cnblogs.com/xutopia/archive/2022/01/05/15768939.html

欄目分類
最近更新