Compuholic
Compuholic

Reputation: 388

Special cases in C++ templates

I currently have to optimize code from another programmer. He left me with a lot of template classes and I would like to make use of functions from Intels IPP-Library to speed up computation. The problem is, that most of the time these functions require that you know what datatypes you are using. So I would like to rewrite the template so that in case the operation can be optimized it will use the specialized code. In case it can't it should fall back to the original code.

The problem is that I would need to check if a certain datatype is being used and I don't know how to do that.

An example. I would like to do something like this:

 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
    }
 }

Any ideas on how to do this? Preferrably without the help of other libraries.

Thank you

Upvotes: 2

Views: 3990

Answers (4)

Scott Langham
Scott Langham

Reputation: 60441

I think you want template specialization. This article explains the basics.

Upvotes: 1

KasF
KasF

Reputation: 212

Use specialization:

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

But if you dont want to rewrite all other functions in Array1D consider using overloading for operator+=.

Upvotes: 1

Andriy Tylychko
Andriy Tylychko

Reputation: 16286

Specialize template like:

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

and in general version use default behavior.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206646

It seems to me that Your use case is an perfect scenario for Template Specialization.

Upvotes: 4

Related Questions