如何对多种类型进行显式专业化? [英] How to do one explicit specialization for multiple types?
问题描述
考虑如下所示的模板函数,如何针对多种类型显式专门化一个版本的函数:
Considering a template function like below how is it possible to do explicitly specialize one version of function for multiple types:
template <typename T>
void doSomething(){
//whatever
}
目的是拥有一个专业而不是多个专业,因为//相同的东西:
The intention is to have one specialization instead of multiple following ones because //something is the same:
void doSomething<int>(){
//something
}
void doSomething<float>(){
//something
}
void doSomething<double>(){
//something
}
有什么方法可以实现一种专业化?
any method to achieve one specialization?
推荐答案
您无法进行模板功能的特殊化.但是您可以在帮助程序类中委派实现,可以从您的函数中使用它.一些基本代码:
You can't make template function specialization. But you could delegate the implementation in a helper class, that can be used from your function. Some skeleton code:
实施模板类并对其进行专门化:
Implement a template class and specialize it:
template< typename T, bool isArithmetic>
struct Something { void operator()() { ... } };
template< typename T, true>
struct Something { void operator()() { ... do something specialized for arithmetic types; } }
然后在模板函数中使用它:
Then use it in the template function:
template< typename T>
void myFunction()
{
Something<T, IsArithmetic<T>::value>()();
}
IsArithmetic是提供有关类型T(选择器)的信息的类.例如,您可以在boost库中找到此类类型信息.
Where IsArithmetic is a class that provides the information about type T (selector). You can find such type info in boost libraries, for example.
这篇关于如何对多种类型进行显式专业化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!