Skip to main content

C++ of the Day #6 - A way to get the type of an expression without evaluating the expression

오늘은 The C++ Source에서 글을 읽다가 발견한 멋진 테크닉 하나 소개합니다. 바로 아래 나와 있는 코드입니다. ((Conditional Love: FOREACH Redux))
// a simple type wrapper
template<class T> struct type2type {};

// convert an expression of type T to an
// expression of type type2type
template<class T> type2type<T> encode_type(T const & t)
{
  return type2type<T>();
}

// convertible to type2type for any T
struct any_type
{
  template<class T> operator type2type<T> () const {
    return type2type<T>();
  }
};

// convert an expression of type T to an
// expression of type type2type without
// evaluating the expression
#define ENCODED_TYPEOF( container ) 
( true ? any_type() : encode_type( container ) )
위의 코드에서 가장 멋진 부분은 바로 가장 아래 줄의 ternary conditional operator (?:) 를 사용한 부분입니다. 이 코드에서 원하는 것은 매크로의 container 부분을 evaluation하지 않고 container의 타입만을 다음 template 함수에 전달하는 것이며 여기서는 type2type<container> 타입의 형태가 전달되기를 원합니다.

물론 여기서 encode_type(container) 를 바로 사용하면 container 부분이 evaluation될 것입니다. ((만약 이 매크로를 사용하면서 container 부분에 get_container_from_db() 같은 함수를 호출하면 매 매크로 사용시마다 db에서 container를 읽으려고 할 것입니다.))

하지만 위의 매크로에선 ternary operator의 조건이 항상 true이기 때문에 컴파일러는 any_type() 객체를 리턴합니다. 즉, container 부분이 evaluation되지 않죠.

그 다음이 재밌는 부분인데 여기서 리턴하는 any_type() 객체의 타입이 any_type이 아닌 type2type<container>가 된다는 점입니다.

이는 ?: operator의 두번째와 세번째 인자의 타입이 같아야 한다는 점을 이용한 것이죠.

이 경우와 같이 두번째와 세번째 인자의 타입이 서로 다른 경우, 컴파일러는 하나의 타입을 나머지 하나와 같게 만들기 위해 형변환을 시도하게 됩니다.

위의 경우 any_type struct에 type2type<container>를 위한 형 변환 operator가 존재함으로 ?: operator의 리턴 타입은 type2type<container>가 됩니다. 만약 type2type<container>도 any_type으로 변환될 수 있었다면 ambiguity 에러가 발생하겠지만 이런 변환을 위한 operator는 존재하진 않기 때문에 여기서는 type2type<container> 타입이 리턴됩니다.

물론 container 부분을 evaluation 하지 않고 말이죠. ;-)

Comments

Popular posts from this blog

CodeHighlighter plugin test page.

This post is for testing CodeHighlighter plugin which uses GeSHi as a fontifier engine. ((Those code blocks are acquired from Google Code Search .)) ((For more supported languages, go CodeHighlighter plugin or GeSHi homepage.)) C++ (<pre lang="cpp" lineno="1">) class nsScannerBufferList { public: /** * Buffer objects are directly followed by a data segment. The start * of the data segment is determined by increment the |this| pointer * by 1 unit. */ class Buffer : public PRCList { public: Buffer() { ++index_; } PHP (<pre lang="php" lineno="4">) for ($i = 0; $i $value = ord( $utf8_string[ $i ] ); if ( $value < 128 ) { // ASCII $unicode .= chr($value); } else { if ( count( $values ) == 0 ) { $num_octets = ( $value } $values[] = $value; Lisp (<pre lang="lisp">) ;;; Assignment (define-caller-pattern setq ((:star var fo...

Textiler plugin test page

This post is for testing Textiler plugin . This plugin uses Textile engine (version 2.0.0). The sample text is come from Textile test page. (Note that the result will be vary according to your CSS options.) Supported wiki syntax Rendering result h2{color:green}. This is a title h3. This is a subhead p{color:red}. This is some text of dubious character. Isn't the use of "quotes" just lazy writing -- and theft of 'intellectual property' besides? I think the time has come to see a block quote. bq[fr]. This is a block quote. I'll admit it's not the most exciting block quote ever devised. Simple list: #{color:blue} one # two # three Multi-level list: # one ## aye ## bee ## see # two ## x ## y # three Mixed list: * Point one * Point two ## Step 1 ## Step 2 ## Step 3 * Point three ** Sub point 1 ** Sub point 2 Well, that went well. How about we insert an <a href="/" title="watch out">old-fashioned hypertext link</a>? Will the quo...

BookCover plugin test page

This post is for testing BookCover plugin . (( The previous test page has some comments from users.)) The 'Books Reading' section in the sidebar is also using this plugin. [ bookcover:1932394613] [bookcover:1932394613] [ bookcover:1590598385(Smart and Gets Things Done)] [bookcover:1590598385(Smart and Gets Things Done)] [ bookcover:1591841380(Wikinomics : How Mass Collaboration Changes Everything)] [bookcover:1591841380(Wikinomics : How Mass Collaboration Changes Everything)] [ bookcover:8995856408] [bookcover:8995856408] [ bookcover:8831793721] [bookcover:8831793721] [ bookcover:9788831793728] [bookcover:9788831793728]