仅覆盖模板中某些类型的函数
Overriding a function only for certain types in template
我有一个带有虚函数的基类:
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()
从基类中获取所有类型,除了某些选定的类型?所以我想要的是能够为int
和long
定义一个覆盖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是int
或long int
,我称之为专用版本。否则,我称之为通用版本,相当于Base::Function()
.
相关文章:
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 将C++子类成员函数(虚拟实现)传递给 C 类型函数指针
- C++ 这里有一个返回 (24) 的布尔返回类型函数
- 使用SFINAE来检测void返回类型函数的存在
- 使用此类型函数有什么优势
- 为什么此函数通过类型函数指针调用后,呼叫明智地行为
- 如何使用无类型函数指针调用C++成员函数
- 模板返回类型函数如何在C++中工作
- 具有通用类型函数的动态库[C ]
- 如何在返回类型函数模板的专用化中使用派生类型?( "couldn't infer template argument" )
- Bon appetit :从 int 返回类型函数在 main() 中打印字符串
- 对于需要其他模板参数的类型函数的部分模板专业化
- c++错误的参数类型-函数指针
- 延迟评估模板类型函数
- 在引用或指针返回类型函数上输入
- 具有指针数据类型的非类型函数模板参数
- STL中使用的C++自定义比较类型(函数谓词与较少结构)
- C++模板基类的非类型函数模板的 using 声明
- 字符串到类型函数,模板专用化使调用统一
- 自由类型函数可以接受 Unicode 文件名吗?