조항43: 학습 처리 템플릿화 기류 내의 명칭

2919 단어
문제 코드
#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 귀속 행위'를 닫기 때문이다. 

좋은 웹페이지 즐겨찾기