11

In the following code, the aim is to have a reference_wrapper<int> b such that when a changes, b also changes however, the opposite should not be allowed that is, a should not change when b changes. I tried two ways: Lines 7 and 8. Line 7 caused compiler to complain that it cannot convert from int to const int while line 8 compiled without problem but the result was not what I wanted (a changed when b changed). Any idea?

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. }
Shibli
  • 5,879
  • 13
  • 62
  • 126

1 Answers1

14

A constant reference could be retrieved by cref.

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

int main() {
    int a = 1;
    reference_wrapper<const int> b = cref(a);
    return 0;
}