I라는 클래스가 'ValueChecker'다음 멤버 함수를 갖는다파생 된 유형을 기본 멤버 템플릿 함수에 전달하는 우아한 방법은 무엇입니까?
:
template<typename T>
bool ValueChecker::checkMe(std::ostringstream &oss, T &me) {
std::cout << "Default checkMe() for " << typeid(me).name() << std::endl;
return true;
}
ValueChecker 파생 클래스의 값에 간단한 확인을 수행하도록 구성되는, 클래스. checkMe()는 결국 다른 파생 클래스에 대한 전문 얻을 것이다 :
class Airplane : public ValueChecker {
friend class ValueChecker;
[...]
}
template<>
bool ValueChecker::checkMe<Airplane>(std::ostringstream &oss, Airplane &me) {
...
/* Actually, this code is generated from a simple file which translates
* a simple language into C++ code. So that a non-developer can write
* the simple checks.
*
* ValueChecker itself has utility functions that may be called in the
* template specialization which are shared across all types.
*/
}
이 작동하지만, 당신이 호출 볼 때 단지 작은 문제가, checkMe의 선언으로있다 :
int main() {
Airplane plane;
std::ostringstream oss;
if(plane.checkMe(oss, plane)) {
cout << "Values are bogus! " << oss.str() << endl;
return 0;
}
I plane.checkMe (oss, plane)를 호출하십시오. 그러나 비행기를 점검하지 않고 다른 비행기를 통과 할 수도 있습니다. 게다가, 호출은 중복인가? 컴파일러는 이론적으로 비행기의 유형에 따라 호출 할 템플릿 함수를 알아야합니다. 그것을 인수로 전달할 필요가 없어야합니까? 어쨌든 마지막 인수를 제거하지 않는 것이 좋습니다. 따라서 이와 같은 전화는 좋을 것입니다 :
if(plane.checkMe(oss)) { ... } // Calls the right template specialization.
나는 그걸 작동시킬 수 없습니다. C++ 전문가가 나를 도와 줄 수 있습니까? 감사.
이 포인터를 typeid에 전달할 수 없습니까? –
CRTP (http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) – Chubsdad
을 평가하셨습니까? 처음에는 다소 이상한 디자인으로 보입니다. '비행기'가 'ValueChecker'에서 파생 된 이유는 무엇입니까? 'checkMe()'가'T '형의 인수를 취하는 이유는 무엇입니까? (질문에서 판단 할 때)'this' 만 체크해야하는 이유는 무엇입니까? – Angew