boost 공부중인데 이것이 왜 컴파일이 가능한지 잘 모르겠습니다.
글쓴이: cpuz / 작성시간: 목, 2009/02/05 - 4:34오후
template<typename KeyType, typename ValueType> class DataType { public: DataType() {} DataType(const KeyType& key, const ValueType& value) : key(key), value(value) {} int compare(const DataType& other) const { return _compare(other, static_cast<boost::is_arithmetic<KeyType>*>(0)); } private: int _compare(const DataType& other, const boost::mpl::true_*) const { return key-other.key; } int _compare(const DataType& other, const boost::mpl::false_*) const { return key.compare(other.key); } public: KeyType key; ValueType value; };
여기서 보시면
int _compare(const DataType& other, const boost::mpl::false_*) const
{
return key.compare(other.key);
}
이 부분입니다.
key 에는 compare 라는 함수도 없는데 이것이 컴파일과 실행이 가능하더라구요.
boost 의 메타프로그래밍 때문인것 같기도 하고...
어떻게 저런 코드가 컴파일이 가능한지 궁금합니다.
Forums:
.
Template은 컴파일러의 치환작업입니다.
해당 자료형에 compare라는 함수가 없다면
컴파일 오류가 발생할겁니다.
...
제 생각에는 해당 KeyType에 대해 boost::is_arithmetic이 boost::mpl::true_로 evaluation되어서, 두 개의 _compare 중 위쪽 것이 불리기 때문에 아래쪽 함수는 불릴 일이 없어서 에러가 안 나는 게 아닐까 싶은데요...
* 근데 저도 template는 잘 모르니까 그냥 그대로 믿지는 마세요...;;;
원래
템플릿은 사용하지 않는 함수에 대해서는 아예 손을 대지를 않습니다. 컴파일도 안하고요 아예 없는 취급합니다. 따라서 저런 코드를 사용 할 수 있는것이죠.
댓글 달기