C ++模板中的特例

时间:2012-01-25 11:04:48

标签: c++ template-specialization

我目前必须优化其他程序员的代码。他给我留下了很多模板类,我想利用Intels IPP-Library中的函数来加速计算。问题是,大多数情况下,这些函数要求您知道正在使用的数据类型。所以我想重写模板,以便在可以优化操作的情况下,它将使用专门的代码。万一它不能回归原始代码。

问题是我需要检查是否使用了某种数据类型,而且我不知道该怎么做。

一个例子。我想做这样的事情:

 template < class Elem > class Array1D
 {
    Array1D<Elem>& operator += (const Elem& a)
    {
    if (typeof(Elem) == uchar)
    {
       // use special IPP operation here
    }
    else
    {
           // fall back to default behaviour
    }
 }

关于如何做到这一点的任何想法?最好没有其他图书馆的帮助。

谢谢

4 个答案:

答案 0 :(得分:4)

在我看来,您的用例是 Template Specialization 的完美场景。

答案 1 :(得分:1)

专门化模板,如:

template<> class Array1D<char>
 {
    Array1D<char>& operator += (const char& a)
    {
       // use special IPP operation here
    }
 }

并且在一般版本中使用默认行为。

答案 2 :(得分:1)

我认为你想要模板专业化。本文介绍了基础知识:

http://www.cprogramming.com/tutorial/template_specialization.html

答案 3 :(得分:1)

使用专业化:

    template<> 
    class Array1D<uchar>
    {
        Array1D<uchar>& operator += (const uchar& a)
        {
        // special behaviour
        }
    };

但是如果你不想重写Array1D中的所有其他函数,请考虑使用operator + =的重载。

相关问题