Skip to main content

C++ of the Day #29 - covariant return types with CRTP

Prototype 패턴을 구현하려면 다음과 같이 각 클래스는 자신만의 clone 함수를 구현해야 합니다. ((c.l.c.m: covariant return types with CRTP)) 간단히 다음과 같죠.
struct B
{
  virtual ~B() {}
  virtual B* clone() const = 0;
};

struct D : B
{
  B* clone() const { ... }
};
이렇게 하면 B*를 가지고 실제 클래스가 무엇인지 관계없이 그 instance의 복제품을 만들어낼 수 있습니다. 하지만 위의 코드를 사용하여 D*를 가지고 복제된 D*를 얻고자 한다면 다음과 같이 casting을 해주어야 합니다.
D* d2 = dynamic_cast<D*>(d->clone());
이런 불편함을 줄이기 위해 C++에서는 overiding한 함수의 리턴 타입이 covariant인 경우 signature가 좀 달라도 overiding을 허용합니다. 일반적으로 두 타입이 모두 pointer나 reference이고 overiding한 함수의 리턴 타입이 원래 리턴 타입을 상속받은 타입이며 같은 cv-qualification을 가지는 경우를 covariant라고 합니다. ((C++98 10.3/5 참조)) 이를 이용하여 위의 코드를 다시 작성하면 다음과 같이 됩니다.
struct D : B
{
  D* clone() const { ... } // change return type from B* to D*
};

D* d2 = d->clone(); // no casting
일반적으로 clone 함수는 자신의 복사 생성자를 사용하여 다음과 같이 구현할 수 있습니다.
D* clone() const {
  return new D(*this);
}
하위 클래스마다 반복되어야 하는 코딩 작업을 줄이기 위해 다음과 같이 CRTP를 사용한 clonable 클래스를 만들어 보겠습니다.
template <class T, class U>
struct clonable : U
{
  T* clone() const {
    T const* d = static_cast<t const*>(this); // (1)
    return new T(*d);
  }
};

struct B
{
  virtual ~B() {}
  virtual B* clone() const = 0;
};

struct D : clonable<D, B>
{
}; 
(1)번 라인에서 dynamic_cast 대신 static_cast를 사용한 것은 이 template의 usage상 clonable과 T는 반드시 상속 관계에 있다는 것을 미리 알 수 있었기 때문입니다. 만약 우리가 원하는 대로 template이 instantiation된다면 D 클래스의 clone함수는 다음과 같이 됩니다.
D* clone() const {
  D const* d = static_cast(this);
  return new D(*d);
}
원하는 대로 covariant return type을 사용하고 있습니다. 그러나... 애석하게도 위의 코드는 컴파일이 되지 않습니다. 컴파일러가 수행하는 작업을 순서대로 따라가면서 원인을 살펴 보죠.
  • struct D : clonable<D, B> 라인에서 컴파일러는 clonable template을 implicitly instantiation합니다. ((C++98 14.7.1/1 참조))
  • 여기서 instantiation되는 clonable은 다음과 같습니다.
struct clonable : B
{
  D* clone() const {
    D const* d = static_cast<d const*>(this); // (1)
    return new D(*d);
  }
};
  • 여기서 clonable의 부모 클래스인 B가 clone함수를 정의하고 있기 때문에 이 함수를 overiding하기 위해서 clonable의 clone() 함수의 리턴 타입은 B의 것과 같거나 covariant type이어야 합니다.
  • 하지만 아직 D 클래스는 완전히 정의되지 않은 상태이기 때문에 D가 B를 상속받는다는 것을 컴파일러가 알지 못합니다.
  • 따라서 컴파일러는 이를 covariant가 아니라고 판단하고 에러를 출력합니다.
위의 이유로 CRTP를 사용한 clonable 클래스는 covariant return type을 가지는 virtual clone()함수를 제공하지 못합니다.

그렇다고 방법이 없는 것은 아닙니다. 다들 아시다시피 derived 클래스에서 base 클래스와 같은 이름의 virtual이 아닌 함수를 선언하면 base 클래스에 있는 이름은 보이지 않게 됩니다. name hiding이라고 불리는 것이죠. 이를 이용하면 다음과 같이 pseudo-covariant return type을 가지는 clonable 클래스를 만들 수 있습니다.
template <class D, class B>
class clonable : B
{
public:
  D* clone() const {
    return static_cast(this->do_clone());
  }
private:
  virtual clonable* do_clone() const {
    return new D(static_cast(*this));
  }
};

class B
{
public:
  B* clone() const {
    return do_clone();
  }
private:
  virtual B* do_clone() const=0;
}; 
위의 clonable에서 중요한 사항은 바로 clone() 함수가 virtual로 정의되어 있지 않다는 점입니다. ((virtual이 아니면서 함수의 signature가 리턴 타입을 제외하면 같죠. 여기서 리턴 타입은 covariant입니다만 실제 overiding 관계가 아니므로 이를 pseudo-covariant return type이라고 부릅니다. 물론 표준적인 용어는 아닙니다.)) 따라서 B의 clone이 불리면 D::clone()이 아닌 B::clone()이 불리게 됩니다.

여기서 두 clone()은 overiding 관계가 아니므로 컴파일러도 covariant인지 아닌지 알아야 필요가 없으며 따라서 에러 없이 컴파일됩니다. 물론 필요한 기능은 모두 동작하면서 말이죠. :-)

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...

C++ of the Day #43 - SQLite3 C++ wrapper #1

The Definitive Guide to SQLite 를 읽다가 공부 겸 해서 C++ wrapper를 만들어 보았습니다. 최대한 C++ 냄새(?)가 나도록 만들어 보았습니다. :-) ((SQLite는 복잡한 관리가 필요없이 사용가능한, 파일이나 메모리 기반의, 라이브러리로 제공되는, 약 250kb 용량의, 대부분의 SQL92문을 지원하는, open source RDB입니다.)) 이 wrapper를 사용하기 위해서는 (당연하게도!) sqlite3 와 (당연하게도?) boost 라이브러리가 필요합니다. 사용 예들을 살펴보는 것으로 설명을 대신합니다. 이번 글에서는 다음과 같은 contacts 테이블이 test.db에 존재한다고 가정합니다. CREATE TABLE contacts ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, phone TEXT NOT NULL, UNIQUE(name, phone) ); Command 먼저 test.db 파일을 사용하기 위해 다음과 같이 파일 이름을 주어 connection 객체를 생성합니다. 생성과 동시에 test.db와 연결이 이루어집니다. ((생성자외에 open() 함수를 사용할 수도 있습니다.)) sqlite3pp::connection conn("test.db"); 다음은 contacts 테이블에 정보를 추가하는 가장 간단한 방법입니다. connection 클래스에서 제공하는 execute 함수를 사용합니다. ((executef 함수를 사용하면 printf와 같은 문법을 사용하여 query문을 작성할 수 있습니다.)) conn.execute("INSERT INTO contacts (name, phone) VALUES ('user', '1234')"); 위와 동일한 작업을 parameterized query를 사용하여 할 수도 있습니다. ((step()함수가 실제 query문을 수행하는 함수입니다. ...

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...