c++, 타입 정의없이 template function call 하는 방법에 대해서
조회수 2358회
한 list에서 서로 다른 타입의 변수를 가질 수 있는 doubly linked list를 구현하고 있습니다.
예시) 11 <-> "aa" <-> 'A' <-> 1.2345
main에서 함수의 타입 정의없이 get(int n) 함수를 통하여 list의 n번째에 저장되어 있는 값을 return하려고 하는데 잘되지 않아 도움을 요청드리려 글을 올립니다 ㅠㅠ
.hpp file
class node_base{
public:
node_base *next;
node_base *prev;
node_base () { next = 0; prev = 0; }
virtual void print () = 0;
virtual int get_node_size () = 0;
};
template <typename T>
class node : public node_base{
public:
T data;
node (const T& val) : data(val) {}
virtual void print (){ cout << data << " "; }
virtual int get_node_size () { return sizeof (data); }
T getData () { return data; }
};
class unvlist{
node_base *head;
public:
int len;
unvlist ();
void print () {
node_base *h = head;
while (h->next != NULL){
h->print ();
h = h->next;
}
h->print ();
}
template <typename T> unvlist (const T* arr, int n);
~unvlist ();
//operator +
//operator ==
template <typename T> void set (int n, const T& val);
template <typename T> T get (int n);
template <typename T> T insert (int n, const T& val);
void erase (int n);
int size ();
void pop_back ();
void pop_front ();
template <typename T> void push_back (const T& val);
template <typename T> void push_front (const T& val);
};
/* get 함수 : list의 n번째에 저장되어 있는 값을 리턴한다. */
template <typename T>
T unvlist :: get (int n){
T retval;
if (n >= len || n < 0){
cout << "'In unvlist::get'-> Out of Bound!!!" << endl;
return 0;
}
if (n >= 0){
node_base *h = head;
for (int i = 0; i < n; i++) { h = h->next; }
retval = static_cast<node<T>*>(h)->getData ();
}
return retval;
}
main.cpp file
int main (){
unvlist *l1 = new unvlist ();
l1->push_back<string> ("aa");
l1->push_back<char> ('A');
l1->push_back<float> (1.2345);
l1->push_front<int> (11);
for (int i = 0; i < 4; i++){
cout << l1->get (i) << " "; // list에 있는 모든 값을 출력
} cout << endl;
return 0;
}
compile error
-
(•́ ✖ •̀)
알 수 없는 사용자
댓글 입력