컴퓨터/C++_STL
template과 iterator 변수 사용하기
adnoctum
2009. 12. 27. 23:00
만약 template에 대한 iterator를 저장할 변수를 선언하려면 GCC의 경우,
[code cpp]
typename
[/code]
를 써야 한다.
다음은 내가 실제 작성하고 있는 코드에서 가져온 예.
[code cpp]
template<class T>
bool bootstrap_resample(
vector<T> *src,
int resample_number,
double (*estimate)(vector<T>*))
{
vector<T>::iterator pos = src->begin();
for(; pos != src->end(); pos++){
// 우선 test
cout << (*estimate)(src) << endl;
}
}
[/code]
위의 함수를GCC로 컴파일하면 에러가 난다. VC++ 6.0에서는 되더군. 에러의 원인은 vector<T>::iterator를 vector<T>에 속하는 멤버 변수로 보고, 여기서 문장이 끝났다고 판단했기 때문에, 뒤에 있는 pos가 없어야 한다는 것이다. 즉,
[code cpp]
class test{
public:
static int aa;
};
[/code]
일 때,
[code cpp]
test::aa pos;
[/code]
와 같은 일이 벌어진 것이다. gcc에서 친절하게도
라고 설명이 나온다. 그 말대로, vector<T>::iterator 자체가 type이니까, 그 뒤에 변수가 온다는 것을 컴파일러에게 알려주기 위해, typename을 쓰라는 것이다.
그러니까,
[code cpp]
typename vector<T>::iterator a;
[/code]
하면 vector<T>::iterator 가 type이 되고, 그 type의 변수 a를 선언한 것이다.
그러므로 에러나지 않는 코드는 다음과 같다.
[code cpp]
template<class T>
bool bootstrap_resample(
vector<T> *src,
int resample_number,
double (*estimate)(vector<T>*))
{
typename vector<T>::iterator pos = src->begin();
for(; pos != src->end(); pos++){
// 우선 test
cout << (*estimate)(src) << endl;
}
}
[/code]
[code cpp]
typename
[/code]
를 써야 한다.
다음은 내가 실제 작성하고 있는 코드에서 가져온 예.
[code cpp]
template<class T>
bool bootstrap_resample(
vector<T> *src,
int resample_number,
double (*estimate)(vector<T>*))
{
vector<T>::iterator pos = src->begin();
for(; pos != src->end(); pos++){
// 우선 test
cout << (*estimate)(src) << endl;
}
}
[/code]
위의 함수를GCC로 컴파일하면 에러가 난다. VC++ 6.0에서는 되더군. 에러의 원인은 vector<T>::iterator를 vector<T>에 속하는 멤버 변수로 보고, 여기서 문장이 끝났다고 판단했기 때문에, 뒤에 있는 pos가 없어야 한다는 것이다. 즉,
[code cpp]
class test{
public:
static int aa;
};
[/code]
일 때,
[code cpp]
test::aa pos;
[/code]
와 같은 일이 벌어진 것이다. gcc에서 친절하게도
error: dependent-name ' std::vector<T, std::allocator<_CharT> >::iterator' is parsed as a non-type, but instantiation yields a type
note: say 'typename std::vector<T, std::allocator<_CharT> >::iterator' if a type is meant
note: say 'typename std::vector<T, std::allocator<_CharT> >::iterator' if a type is meant
라고 설명이 나온다. 그 말대로, vector<T>::iterator 자체가 type이니까, 그 뒤에 변수가 온다는 것을 컴파일러에게 알려주기 위해, typename을 쓰라는 것이다.
그러니까,
[code cpp]
typename vector<T>::iterator a;
[/code]
하면 vector<T>::iterator 가 type이 되고, 그 type의 변수 a를 선언한 것이다.
그러므로 에러나지 않는 코드는 다음과 같다.
[code cpp]
template<class T>
bool bootstrap_resample(
vector<T> *src,
int resample_number,
double (*estimate)(vector<T>*))
{
typename vector<T>::iterator pos = src->begin();
for(; pos != src->end(); pos++){
// 우선 test
cout << (*estimate)(src) << endl;
}
}
[/code]