gpt4 book ai didi

c++ - 使用 boost::ref 传递对取值函数的引用

转载 作者:太空狗 更新时间:2023-10-29 23:36:23 26 4
gpt4 key购买 nike

我对 boost::ref 的使用感到困惑。我不明白为什么有人会想要执行以下操作 -

void f(int x)
{
cout << x<<endl;
x++;
}

int main(int argc, char *argv[])
{
int aaa=2;
f(boost::ref(aaa));
cout << aaa<<endl;
exit(0);
}

将 ref 传递给函数有什么用。我总是可以按值(value)传递。也不是 ref 实际通过了。上面aaa在main中的值只保持2。

boost ref 到底有什么用处?

在这种情况下是否可以使用 boost::ref。我想将迭代器引用传递给 std::sort 函数。通常排序适用于迭代器拷贝 - boost::ref 是否也适用于引用? (不对 std::sort 进行任何更改)

最佳答案

I dont understand why any one would want to do the following

他们不会。这不是 boost::ref(或现在的 std::ref)的目的。如果函数按值接受参数,则无法强制它改为按引用接受参数。

Where exactly is boost ref useful?

通过实例化引用(包装)类型的模板,而不是值类型,它可以用来使函数模板表现得好像它通过引用接收参数:

template <typename T>
void f(T x) {++x;}

f(aaa); cout << aaa << endl; // increments a copy: prints 0
f(ref(aaa)); cout << aaa << endl; // increments "a" itself: prints 1

一个常见的特定用途是将参数绑定(bind)到函数:

void f(int & x) {++x;}

int aaa = 0;
auto byval = bind(f, aaa); // binds a copy
auto byref = bind(f, ref(aaa)); // binds a reference

byval(); cout << aaa << endl; // increments a copy: prints 0
byref(); cout << aaa << endl; // increments "a" itself: prints 1

Is it possible to use boost:;ref in this scenario. I want to pass iterator refernce to std::sort function. normally the sort works on iterator copies - will boost::ref make it work for references also?

没有;引用包装器不满足迭代器要求,因此您不能在标准算法中使用它。如果可以,那么如果许多算法需要制作迭代器的独立拷贝(许多算法,包括大多数 sort 实现,都必须这样做),它们就会出错。

关于c++ - 使用 boost::ref 传递对取值函数的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16460858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com