仅覆盖模板中某些类型的函数

Overriding a function only for certain types in template

本文关键字:类型 函数 覆盖      更新时间:2023-10-16

我有一个带有虚函数的基类:

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

和派生模板类:

template <class T> class Derived : public Base
{
public:
  virtual void Function();
};

有没有办法使Function()从基类中获取所有类型,除了某些选定的类型?所以我想要的是能够为intlong定义一个覆盖Function()

void Derived<int>::Function()
{
  cout << "overriden version 1" << endl;
}
void Derived<long>::Function()
{
  cout << "overriden version 2" << endl;
}

并且对于所有其他类型具有默认版本的 Function(),而没有为它们显式定义Function(),因此输出

int main ()
{
  Derived<int> derivedInt;
  derivedInt.Function();
  Derived<long> derivedLong;
  derivedLong.Function();
  Derived<double> derivedDouble;
  derivedDouble.Function();
}

overriden version 1
overriden version 2
default version

可能吗?

类模板的成员函数实际上是函数模板,因此您可以专门化它们:

template <typename T> class Foo
{
    void Function();
};
template <typename T> void Foo::Function() { /* ... */ }
template <> void Foo<int>::Function() { /* ... */ }

是的,通过专门Derived

.
  • 编写没有它的通用版本(它将从Base继承它)
  • 专用Derived以覆盖

简单的方案,但它有效。

第一个解决方案(使用 typeid 运算符):

#include <iostream>
#include <typeinfo>
using namespace std;
class Base
{
public:
    virtual void Function();
};
void Base::Function()
{
    cout << "default versionn";
}
template<typename T>
class Derived : Base
{
public:
    virtual void Function();
};
template<typename T>
void Derived<T>::Function()
{
    if(typeid(T) == typeid(int)) // check if T is an int
    {
        cout << "overriden version 1n";
    }
    else if(typeid(T) == typeid(long)) // check if T is a long int
    {
        cout << "overriden version 2n";
    }
    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;
}

我使用 typeid 运算符检查 T 是 int 还是 long int ,如果是,我打印"覆盖版本 [数字]"。如果不是,我调用Base::Function(),这将打印"默认版本"

注意:要使用 typeid 运算符,您需要包含头文件typeinfo

第二种解决方案(使用模板专用化):

// class declarations as before
template<typename T>
void Derived<T>::Function()
{
    Base::Function(); // call default version
}
template<>
void Derived<int>::Function()
{
    cout << "overriden version 1n";
}
template<>
void Derived<long>::Function()
{
    cout << "overriden version 2n";
}
int main()
{
    Derived<int> di;
    Derived<long> dl;
    Derived<float> df;
    di.Function();
    dl.Function();
    df.Function();
    return 0;
}

在这里,我解决了您的模板专业化问题。如果T是intlong int,我称之为专用版本。否则,我称之为通用版本,相当于Base::Function().