Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在c++;_C++_Templates - Fatal编程技术网

C++ 如何在c++;

C++ 如何在c++;,c++,templates,C++,Templates,我对模板感到困惑。我有两个全班;特殊整数类和特殊字符串类。它们都有一个公共类作为超类和 一个特殊的班级 class Special_Integer: public Internal_Integer, public Message_System class Special_String: public Internal_String, public Message_System 我只需要执行它们共同的功能,例如 Special_Integer.sendMessage() Special_Str

我对模板感到困惑。我有两个全班;特殊整数类和特殊字符串类。它们都有一个公共类作为超类和 一个特殊的班级

class Special_Integer: public Internal_Integer, public Message_System

class Special_String: public Internal_String, public Message_System
我只需要执行它们共同的功能,例如

Special_Integer.sendMessage()
Special_String.sendMessage()
在Message_系统类中

现在我想创建一个std::list或std::vector,这样我就不必创建两个类似于

std::list< boost::shared_ptr<Special_Integer> > exampleList;
std::list< boost::shared_ptr<Special_String> > exampleList2;
std::listexampleList;
std::listexampleList2;
但如果我能把它们放在一个列表中

std::list< boost::shared_ptr<template_Type> > exampleList;
std::listexampleList;

我认为这是可能的。

实际上,在这种情况下,您并不真正需要模板。两个类共享一个基类,所以只需使用多态性

std::list<boost::shared_ptr<Message_System>> exampleList;
派生类可以
覆盖那些

void Special_Integer::sendMessage() override;
void Special_String::sendMessage() override;

然后,当您调用每个
sendMessage
时,将以多态方式调用正确的派生方法。

工作正常。谢谢。一个后续问题;如果我想运行一个非公共函数,我将执行类似boost::shared\u ptr foo=boost::dynamic\u pointer\u cast(*it)的动态转换;如果(foo){}@user1566277是,这是检查强制转换是否正确的正确方法。然后可以调用特定于一个派生类或另一个派生类的方法。谢谢。但是代码看起来很难看。考虑它做了十几种类型。每次我需要声明新变量(foo)时,检查它,然后在块内执行。我想我不能为每种类型创建一个公共执行块,因为我必须进行动态的_转换。所以基本上很多if语句和代码看起来很相似,因为它在每个块中为不同的子类调用相同的函数。
void Special_Integer::sendMessage() override;
void Special_String::sendMessage() override;