C++ – 派生类访问模板基类(templatized base class)命名

派生类访问模板基类(templatized base class)命名


本文地址: http://blog.csdn.net/caroline_wendy/article/details/23993691


派生类继承模板化基类成员函数, 默认是无法訪问,
模板化基类的命名. 

原因模板的定制化有可能取消某些函数, 为了能在编译期检測出错误, 所以默认无法訪问.


派生类訪问模板化基类, 包括三种方法:

1. 调用基类函数时, 使用"this->", 指明调用的类, 是本类, 在编译时, 能够进行检查;

2. 使用using声明式, 能够把基类的函数引入派生类, 在编译时, 能够进行检查;

3. 使用显示修饰(explicit qualification), 不推荐, 显示修饰会屏蔽virtual的动态绑定;


本例为: 派生类, 调用基类的函数, 重写改动格式, 进行输出;


代码:

/*
 * test.cpp
 *
 *  Created on: 2014.04.18
 *      Author: Spike
 */

/*eclipse cdt, gcc 4.8.1*/

#include <iostream>
#include <string>
#include <memory>

using namespace std;

class CompanyCaroline {
public:
	void sendCleartext(const std::string& msg) {
		std::cout << "Cleartext: " << msg << std::endl;
	}
	void sendEncrypted(const std::string& msg) {
		std::cout << "Encrypted: " << msg << std::endl;
	}
};

struct MsgInfo {
	std::string cleartext;
	std::string encrypted;
};

template<typename Company>
class MsgSender {
public:
	void sendClear(const MsgInfo& info) {
		std::string msg = info.cleartext;
		Company c;
		c.sendCleartext(msg);
	}
	void sendSecret(const MsgInfo& info) {
		std::string msg = info.encrypted;
		Company c;
		c.sendEncrypted(msg);
	}
};

template<typename Company>
class LoggingMsgSender : public MsgSender<Company> {
public:
	//using MsgSender<Company>::sendClear; //方法二
	void sendClearMsg(const MsgInfo& info) {
		std::cout << "Log Begin : ";
		//sendClear(info);
		this->sendClear(info); //方法一
		//MsgSender<Company>::sendClear(info); //方法三, 会关闭虚绑定的行为, 不建议
	}
};


int main() {
	MsgInfo mi = {"Clear", "Encrypted"};
	LoggingMsgSender<CompanyCaroline> lms;
	lms.sendClearMsg(mi);

	return 0;
}

输出:

Log Begin : Cleartext: Clear

C++ - 派生类访问模板基类(templatized base class)命名

版权声明:本文博主原创文章,博客,未经同意不得转载。

原文链接: https://www.cnblogs.com/zfyouxi/p/4830054.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ - 派生类访问模板基类(templatized base class)命名

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/222171

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 上午11:37
下一篇 2023年2月13日 上午11:38

相关推荐