常量reference_wrapper

Shi*_*bli 2 c++ const c++11 reference-wrapper

在下面的代码中,目标是具有reference_wrapper<int> b这样一种特性,即当a更改时b也会更改,但是不允许相反,也就是说,a更改时不应b更改。我尝试了两种方法:第7行和第8行。第7行导致编译器抱怨它无法从第8行编译时毫无问题地转换为intconst int但是结果却不是我想要的(a更改时b更改了)。任何的想法?

1.  #include <iostream>
2.  #include <functional>
3.  using namespace std;
4.  
5.  int main() {
6.      int a = 1;
7.      //reference_wrapper<const int> b = ref(a);
8.      //const reference_wrapper<int> b = ref(a);
9.  return 0;
10. }
Run Code Online (Sandbox Code Playgroud)

小智 8

常量引用可以通过检索cref

#include <iostream>
#include <functional>
using namespace std;

int main() {
    int a = 1;
    reference_wrapper<const int> b = cref(a);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)