首页 > 其他分享 >类内函数的override问题-方法

类内函数的override问题-方法

时间:2023-01-18 23:56:17浏览次数:41  
标签:Function 函数 void Derived Base 类内 override class template

Question:

have a base class with a virtual function:

class Base
{
public:
  virtual void Function();
};
void Base::Function()
{
  cout << "default version" << endl;
}

and a derived template class:

template <class T> class Derived : public Base

{
public:
  virtual void Function();
};
If want to have a way to make Function() be taken from the base class for all types, except some chosen ones?

Solution1: (using type-id  operator)
#include <iostream>
#include <typeinfo>
using namespace std;

class Base
{
public:
    virtual void Function();
};

void Base::Function(){
    cout<<"default version"<<endl;
}

template<typename T>   //using template keyword for type branches
class Derived : Base   //from Base class
{
public:
    virtual void Function();
};


template<typename T>  //using template keyword for type branches
void Derived<T>::Function()
{
    if(typeid(T) == typeid(int)) // check if T is an int
    {
        cout << "overriden version 1\n";
    }
    else if(typeid(T) == typeid(long)) // check if T is a long int
    {
        cout << "overriden version 2\n";
    }
    else // if T is neither an int nor a long
    {
        Base::Function(); // call default version
    }
}

int main()
{
    Derived<int> di;
    Derived<long> dl;
    Derived<float> df;
    
    di.Function();
    dl.Function();
    df.Function();
    return 0;
}

 

同时用template specilization也可以解决这个问题

标签:Function,函数,void,Derived,Base,类内,override,class,template
From: https://www.cnblogs.com/selfmade-Henderson/p/17060891.html

相关文章

  • 解决:无法将“php”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
    如果我们已经安装了PHP或者其他集成环境,但是在命令行执行php命令时还是报这个错误  那是因为没有配置环境变量在此电脑上右键,然后看下面这张图  然后在Path变......
  • m基于效用函数的联合资源分配matlab仿真,对比PF,CUBP以及DUBP三种方法
    1.算法描述 表示基站n到用户m是否连接。 1.1C-CUBP   主要涉及到的公式有: 1.2C-DUBP 主要涉及到的公式有: 2.仿真效果预览matlab2022a仿真......
  • 函数的基本使用
    函数简介函数的语法结构函数的定义与调用函数简介name_list=['jason','kevin','oscar','jerry']print(len(name_list))'''突然无法使用len'''count=0fori......
  • 函数的参数
    函数的参数形式参数 在函数定义阶段括号内填写的参数简称'形参'实际参数 在函数调用阶段括号内填写的参数简称'实参'++++++++++++++++++++++++++++++++++++++++++++......
  • C语言基础--函数
    目录一、什么是函数二、函数的创建三、函数的使用四、返回值的使用五、什么是形参和实参六、默认值形参七、函数的递归一、什么是函数编程中的函数是将一些需要复用的代......
  • 常量、函数、三大语句--(基本)
    常量的知识点1.字面常量比如:2、3、3.14就是字面上的不变的量 2.const修饰的常变量const修饰一个变量的时候,变量具有了常属性,也就是不能通过赋值去改变变量了,但它实际上......
  • 进程监视子进程之wait函数
    父进程监视子进程,需要知道子进程状态什么时候改变状态改变有哪些:子进程终止子进程收到停止信号而停止运行,收到恢复信号而运行wait函数作用监视进程什么时候终止回......
  • 35_输出素数(函数)
    一、python收获:1、python自己可能用到的快捷注释:选中ctrl+/、三个引号‘’‘2、根号方式:二次的话sqrt(但要importmath,math.sqrt)、或者使用内置函数pow(i,次数(比如0.5))......
  • py之循环,函数
    循环a=1whilea<10: print(a) a+=1 a=[123,1235,123124,1231]whilea: a1=a.pop() print(a1) fora1ina: print(a1) foriinrange(4): print(a[i]) ......
  • C++入门篇之重载运算符和重载函数
    C++允许在同一作用域中的某个函数 和运算符 指定多个定义,分别称为函数重载 和运算符重载。重载声明是指一个与之前已经在该作用域内声明过的函数或方法具有相同名称的声......