欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

c++中的bind使用方法

 更新時(shí)間:2022年01月06日 09:43:33   作者:xutopia  
bind是這樣一種機(jī)制,它可以預(yù)先把指定可調(diào)用實(shí)體的某些參數(shù)綁定到已有的變量,產(chǎn)生一個(gè)新的可調(diào)用實(shí)體,這種機(jī)制在回調(diào)函數(shù)的使用過程中也頗為有用。接下來通過本文給大家介紹c++中的bind使用方法,感興趣的朋友一起看看吧

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

std::bind函數(shù)定義在頭文件functional中,是一個(gè)函數(shù)模板,它就像一個(gè)函數(shù)適配器,接受一個(gè)可調(diào)用對(duì)象(callable object),生成一個(gè)新的可調(diào)用對(duì)象來“適應(yīng)”原對(duì)象的參數(shù)列表。一般而言,我們用它可以把一個(gè)原本接收N個(gè)參數(shù)的函數(shù)fn,通過綁定一些參數(shù),返回一個(gè)接收M個(gè)(M可以大于N,但這么做沒什么意義)參數(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問其成員的對(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 來自 std::placeholders ,并表示將來會(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)用
 
    // 常見使用情況:以分布綁定 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

到此這篇關(guān)于c++中的bind使用方法的文章就介紹到這了,更多相關(guān)c++ bind使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論