24,860
社区成员




#include <boost/ref.hpp>
#include <boost/noncopyable.hpp>
using namespace boost;
class A:public noncopyable //A是一个不可拷贝的类
{
public:
A(){};
~A(){};
};
void print(A a){}; //需要传值的函数
void main()
{
A a; //不可拷贝的对象
print(ref(a)); //用ref封包装依旧报错
}
#include <functional>
#include <iostream>
void f(int& n1, int& n2, const int& n3)
{
std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
++n1; // increments the copy of n1 stored in the function object
++n2; // increments the main()'s n2
// ++n3; // compile error
}
int main()
{
int n1 = 1, n2 = 2, n3 = 3;
std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));
n1 = 10;
n2 = 11;
n3 = 12;
std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
bound_f();
std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
}
这里的void f(int& n1, int& n2, const int& n3)都是传的引用啦,所以不管参数是否是可拷贝的[/quote]
ref reference_wrapper就是为了解决bind的函数有引用参数的问题。
要是没ref reference_wrapper的话,bind 有引用参数的函数就逻辑错误了。
reference_wrapper的目的,作者都没搞清楚。#include <functional>
#include <iostream>
void f(int& n1, int& n2, const int& n3)
{
std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
++n1; // increments the copy of n1 stored in the function object
++n2; // increments the main()'s n2
// ++n3; // compile error
}
int main()
{
int n1 = 1, n2 = 2, n3 = 3;
std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));
n1 = 10;
n2 = 11;
n3 = 12;
std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
bound_f();
std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
}
这里的void f(int& n1, int& n2, const int& n3)都是传的引用啦,所以不管参数是否是可拷贝的