C++ 学习笔记(12)模拟 std::ref

#include <bits/stdc++.h>
#define rep( i , j , n ) for ( int i = int(j) ; i < int(n) ; ++i )
#define dew( i , j , n ) for ( int i = int(n-1) ; i > int(j) ; --i )
#define _PATH __FILE__ , __LINE__
typedef std::pair < int , int > P ;
using std::cin ;
using std::cout ;
using std::endl ;
using std::string ;

namespace YHL {
	template<typename T>
	class refHolder {
	private:
		T& ref ;
		refHolder() = delete ;
		refHolder& operator=(const refHolder &) = delete ;
	public:
		refHolder(T& _ref) : ref(_ref) {}
		refHolder(const refHolder& _ref) : ref(_ref) {}
		operator T&() const {
			return ref ;
		}
	} ;

	template<typename T>
	inline refHolder<T> getRef(T &ref) {
		return refHolder<T>(ref) ;
	}

	template<typename T>
	void example(T someOne) {
		someOne <<= 1 ;
	}
}

int main () {
	using namespace YHL ;
	auto ans = 1 ;
	cout << "ans = " << ans << endl ;
	example(ans) ;
	cout << "ans = " << ans << endl ;
	example(getRef(ans)) ;
	cout << "ans = " << ans << endl ;
	return 0 ;
}

猜你喜欢

转载自blog.csdn.net/nishisiyuetian/article/details/81603932