본문 바로가기
Language/C++

[C++] std::ref, std::reference_wrapper

by 어발 2023. 9. 1.

std::ref()

- "call by value"를 사용하는 함수 템플릿에 객체를 참조로 보내고 싶을때 사용

- <functional>헤더, C+11부터 지원

std::reference_wrapper

#include <iostream>

template<typename T>
struct reference_wrapper {
	T* obj;
public:
	reference_wrapper(T& t) : obj(&t) {}
    operator T&() { return *obj; }
};

int main() {
	int n = 0;
    reference_wrapper<int> rw = n;
    
    int& r = rw; // rw.operator int&()
    r = 100;
    
    std::cout << n << std::endl; // 100 출력
}

 

728x90

'Language > C++' 카테고리의 다른 글

[C++] std::packaged_task  (0) 2024.12.18
[C++] std::promise, std::future  (0) 2024.12.04
[C++] std::thread  (0) 2023.09.01
[C++] std::chrono  (0) 2023.09.01
[C++] std::this_thread  (0) 2023.09.01

댓글