가변클래스 템플릿에서 생성자를 어떤 식으로 만들어야 하나요?
글쓴이: dltkddyd / 작성시간: 월, 2013/12/09 - 4:35오후
가변클래스템플릿을 만들었습니다. 그런데 컴파일시 다음과 같은 오류가 뜹니다.
file.cc: In constructor 'AnyExtraction:AnyExtraction(ExtractedType, Args ...)[with ExtractedType=double, Args={int, float}]';
file.cc: instantiated from here
file.cc:error: type 'AnyExtraction' is not a direct base of 'AnyExtraction'
#include <iostream> using namespace std; #include <type_traits> template<typename ExtractedType=int, typename... Args> class AnyExtraction { public: static const int value=0; ExtractedType exValue; AnyExtraction(ExtractedType _exValue, Args... args):AnyExtraction(args...) {//여기에서 에러가 난답니다. exValue=_exValue; cout<<"exValue is "<<exValue<<endl; cout<<"The number of remainers is "<<sizeof...(Args)<<endl; } AnyExtraction(ExtractedType _exValue) { exValue=_exValue; cout<<"exValue is "<<exValue<<endl; } }; int main() { AnyExtraction<double,int, float> obj1(5.5, 10, 4.5);//여기 이 객체가 생성될 때 return 0; }
제가 예상했던 결과는 이렇습니다. obj1이라는 객체가 생성되는 과정에서 생성자가 호출될 때 ExtractedType은 타입을 하나씩 추출해서 exValue라는 멤버에 순서대로 값을 저장하도록 합니다. 그리고 결과를 cout으로 출력하기 전에 이니셜라이져로 생성자를 호출해서 다음 값을 순서대로 exValue에 저장합니다. 이런 식으로 하면
exValue is 4.5
exValue is 10
The number of remainers is 1
exValue is 5.5
The number of remainer is 2
그런데 에러부터 납니다. 무엇을 어떻게 고쳐야 의도하던대로 이 클래스가 작동될까요?
Forums:
템플릿 클래스는 인자가 바뀌면 다른 타입이 됩니다.
템플릿 클래스는 인자가 바뀌면 다른 타입이 됩니다. 예를 들어 vector<int>와 vector<double>은 다른 타입니다.
delegate constructor를 사용하는 것이므로 당연히 같은 타입의 생성자만 호출이 가능합니다.
인자가 하나줄어든 템플릿 클래스는 다른 타입의 템플릿 클래스이므로 이렇게 짜는건 불가능합니다.
생성자가 아닌 함수를 이용하세요.
그러면 다른 방법을 고민해봐야 겠습니다.
답변 감사합니다.
본인 맞습니다.
인증샷
우헤헤헤... 로 대신합니다.
댓글 달기