조항43: 학습 처리 템플릿화 기류 내의 명칭
#include <iostream>
using namespace std;
class CompanyA
{
public:
void sendCleartext(const std::string& msg);
void sendEncrypted(const string& msg);
};
class CompanyB
{
public:
void sendCleartext(const std::string& msg);
void sendEncrypted(const string& msg);
};
class MsgInfo{};
template<typename Company>
class MsgSender
{
public:
void sendClear(const MsgInfo& info)
{
string msg;
Company c;
c.sendCleartext(msg);
}
void sendSecret(const MsgInfo& info)
{
string msg;
Company c;
c.sendEncrypted(msg);
}
};
template<typename Company>
class LoggingMsgSender:public MsgSender<Company>
{
public:
void sendClearMsg(const MsgInfo& info)
{
sendClear(info);
}
};
상술한 코드는 컴파일을 통과할 수 없다. 적어도 규칙을 엄수하는 컴파일러에게는.이런 컴파일러는 sendClear가 존재하지 않는다고 불평할 것이다.sendClear가 기본 클래스에 있는 것을 보았지만 컴파일러는 그것들을 볼 수 없었다.그 이유는 이른바 템플릿 전특화가 있기 때문이다. 이 특화판의 기본 클래스에sendClear라는 함수가 없을 수 있기 때문에 C++가 이 호출을 거부한 이유는 기본 템플릿이 특화될 수 있다는 것을 알고 그 특화버전은 일반 템플릿과 같은 인터페이스를 제공하지 않을 수도 있기 때문이다.따라서 템플릿 클래스에서 계승된 이름을 찾는 것을 거부한다.
예를 들어 암호화 커뮤니케이션만 사용하는 기업이 있습니다.
class CompanyZ
{
public:
void sendEncrypted(const std::string& msg);
};
이전에 정의된 MsgSender 템플릿은 CompanyZ에 적합하지 않습니다. 이 템플릿은sendClear가 명문을 보내는 함수를 제공하기 때문입니다.따라서 CompanyZ를 위한 MsgSender Premium Edition을 만듭니다.
template<>
class MsgSender
{
public:
void sendSecret(const MsgInfo& info)
{.........}
};
그러나 LoggingMsgSender 템플릿이 CompanyZ로 전달되는 경우 오류가 발생합니다.
template<typename Company>
class LoggingMsgSender:public MsgSender<Company>
{
public:
void sendClearMsg(const MsgInfo& info)
{
sendClear(info); // Company = CompanyZ,
}
};
해결 방법:
1. 기본 함수를 호출하기 전에 "this->"를 추가합니다.
template<typename Company>
class LoggingMsgSender:public MsgSender<Company>
{
public:
void sendClearMsg(const MsgInfo& info)
{
this->sendClear(info); // , sendClear
}
};
2. using을 사용하여 선언하기
template<typename Company>
class LoggingMsgSender:public MsgSender<Company>
{
public:
using MsgSender<Company>::sendClear; // , sendClear base class
void sendClearMsg(const MsgInfo& info)
{
sendClear(info); // , sendClear
}
};
3. 호출된 함수가 기본 클래스에 있음을 명확히 지적한다.
template<typename Company>
class LoggingMsgSender:public MsgSender<Company>
{
public:
void sendClearMsg(const MsgInfo& info)
{
Msgsender<Company>::sendClear(info); // , sendClear
}
};
그러나 이것은 흔히 가장 만족스럽지 못한 해법이다. 만약에 가상 함수가 호출된다면 상술한 명확한 자격 수식은'virtual 귀속 행위'를 닫기 때문이다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.