템플릿으로 할 수 있습니다.
편집 : 추가 정보를 기반으로 한 새로운 구현입니다.
template <typename T>
void lookup(int idNum, T* &ptr) {
auto it = mymap.find(idNum);
if (it == mymap.end()) {
ptr = 0;
} else {
ptr = dynamic_cast<T*>(*it); // Shape must have a virtual member function
}
}
또는 당신이 선호 수 있습니다 : mymap
는 std::map<int, Shape*>
경우 그런
template <typename T>
T* lookup(int idNum) {
auto it = mymap.find(idNum);
if (it == mymap.end()) {
return 0;
}
return dynamic_cast<T*>(*it);
}
자체가 재미의 전체 힙이 Circle *circle = database.lookup<Circle>(123);
분명히 다형성 용기처럼 부르지 만, 나는거야 그걸 정렬했다고 가정하십시오. 내가 빠뜨린 어딘가에 shared_ptr
이있을 수 있습니다.
올드 구현 나는 DB는 POD의 사본을 저장할 수 있습니다 생각했을 때 :
template <typename T>
void lookup(int idNum, T* &ptr) {
void *theresult = // something based on idNum
// some check needed here that theresult really is the right type.
// how you do this depends on the database, but suppose that
// the database gives us some integer "type" which indicates the type
if (type != type_constant<T>::value) {
ptr = 0;
} else {
ptr = static_cast<T*>(theresult);
}
}
type_constant는 "유형의 특성"의 예입니다, 당신이 좋아 구현 :
template <typename T>
struct type_constant {};
template <>
struct type_constant<Circle> {
static const int value = 1;
};
template <>
struct type_constant<Rectangle> {
static const int value = 2;
};
// etc...
IMO
, 이것은 정말로 데이터베이스 질문입니다. 당신은 또한 어떤 DB를 말하지 않습니다. SQL 키워드 "LIKE"를 살펴 보겠습니다. – JustBoo
유형 정보를 데이터베이스에 전달하는 방법은 무엇입니까? (또는 내가 말해야 할 것은, 데이터베이스가 그것을 어떻게 받아 들여야 하는가?) –
데이터베이스가이 정보를 가지고 * 수행하기를 원한다면, 당신은 원 - 특정 코드, 몇몇 직사각형 특정 코드 등을 써야 할 것이다. 광고 구역. 질문은 *이 코드를 어디에 넣고 싶은지입니다. 데이터베이스에서 수행 할 작업을 지정할 수 있습니까? – Beta