C++ 類中的 reference_wrapper
C++ 中的 reference_wrapper 是一個類模板,透過封裝一個引用到型別為 T 的可複製和可賦值物件的引用來提供幫助。std::reference_wrapper 的例項基本上是物件,但它們可以轉換成 T&。所以我們可以將它們作為引數用於需要引用型別作為引數的函式。
例子程式碼
#include <iostream> #include <functional> using namespace std; int main () { char a = 'h', b = 'e', c = 'l', d = 'l', e = 'o' , f = 'W', g = 'o', h = 'r', i = 'l', j = 'd'; reference_wrapper<char> ref[] = {a, b, c, d, e, f, g, h, i, j}; //creating reference array for (char& s : ref) cout << s; cout <<endl; return 0; }
輸出
soumyadeep@soumyadeep-VirtualBox:~$ ./a.out helloWorld soumyadeep@soumyadeep-VirtualBox:~$
廣告