mixing templates with polymorphism(将模板与多态性混合)
本文介绍了将模板与多态性混合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class A
{
friend void foo();
virtual void print_Var() const{};
};// does not contain variable Var;
template<class T>
class B : public A
{
T Var;
public:
B(T x):Var(x){}
void print_Var() const override
{
std::cout<<Var<<std::endl;
}
};
void foo()
{
std::array<std::unique_ptr<A>, 3> Arr = {
std::make_unique<B<int>>(100),
std::make_unique<B<int>>(20),
std::make_unique<B<std::string>>("Hello Stackoverflow")
};
std::shuffle(Arr.begin(), Arr.end(), std::mt19937(std::random_device()())); // 3rd parameter generated by Clang-Tidy
for (auto &i: Arr)
{
i->print_Var(); // OK
// auto z = i->Var // no member named Var in A
// obviously base class does not contain such variable
// if (i->Var==20) {/* do something*
织梦狗教程
本文标题为:将模板与多态性混合


基础教程推荐
猜你喜欢
- 使用基本数据类型,并输出它们的值,int,floa 1970-01-01
- \a序列表示“钟”字符。 1970-01-01
- C++ #define 1970-01-01
- C++函数调用运算符()重载 1970-01-01
- 读取名字和身高并显示信息 1970-01-01
- C++条件编译 1970-01-01
- C语言库difftime()函数 1970-01-01
- 使用printf()显示int类型的变量 1970-01-01
- C++ - 指向对象的向量的性能与对象的性能 2022-10-18
- C++递增指针 1970-01-01