• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
鱼市口
博客园    首页    新随笔    联系   管理    订阅  订阅
类内函数的override问题-方法

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也可以解决这个问题
posted on 2023-01-18 23:42  鱼市口  阅读(16)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3