헤더파일

C++ Explicit Conversion Operator 본문

C++

C++ Explicit Conversion Operator

헤더파일 2020. 3. 25. 22:30
void true_function() {}

class istream   // basic_istream
{
public:
	bool fail() { return false; }

	// 방법 1. bool 로 변환 - 단점. shift  연산이 허용된다.
	//operator bool() { return fail() ? false : true; }

	// 방법 2. void* 로의 변환 - C++ 98/03
	// operator void*() { return fail() ? 0 : this; }

	// 방법 3. 함수 포인터로의 변환.
	//typedef void(*F)();
	//operator F() { return fail() ? 0 : &true_function; }

	// 방법 4. 멤버 함수 포인터로의 변환. - Safe BOOL
	//          if() 문에 넣을수 있는 side effect가 가장 적다..
	struct Dummy
	{
		void true_function() {}
	};
	typedef void(Dummy::*F)();
	operator F() { return fail() ? 0 : &Dummy::true_function; }

};
istream cin;

int main()
{
	int n = 0;
	if ( cin ) {}
//	cin << n;
//	delete cin;

//	void(*f)() = cin;
}

객체를 조건문에서 그대로 쓰고자 할 때는 문제가 되는 경우가 많습니다.

제일 안전한 방법은 멤버 함수 포인터로의 변환인데 상당히 복잡합니다.

 

class istream
{
public:
	bool fail() { return false; }

	// C++11 변환 연산자 앞에도 explicit를 붙일수 있다.
	// 암시적 변환은 error. 명시적 허용
	// if 문안에 객체를 넣을수도 있다.
	explicit operator bool() { return fail() ? false : true; }
};
istream cin;

int main()
{
	int n = 0;

	//bool b = cin; //error
	bool b = static_cast<bool > (cin); // ok

	//cin << n; // error

	if ( cin ) {}  // ok
	if ( cin == false ) {}// error
}

 

C++ 11 부터는 explicit conversion operator 가 지원되기 때문에 이런식으로 작성한다면 간단히 만들 수 있습니다.

if 문에 객체 이름을 그대로 쓰는 것은 명시적 변환이 되진 않았지만 예외조건으로 허용해줍니다.

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

C++ static_assert  (0) 2020.03.26
c++ Brace Init  (0) 2020.03.25
c++ 변환 연산자, 변환 생성자  (0) 2020.03.23
C++17 if 초기화, if constexpr, 구조체 바인딩  (1) 2020.03.23
c++ Trivial  (2) 2020.03.19
Comments