user63898
user63898

Reputation: 30885

c++ template in function

I want to make a generic Array function. In my API, I have generic container that I need to cast to the right class, but I want to make it generic

template<class T>
void UT::printArray(CCArray* arr, T type)
{
    CCObject *aIt = NULL;  
    CCARRAY_FOREACH(arr,aIt )
    {
        T *aElm = static_cast<T*>(aIt );
        int col = aElm ->getColNum(); 
        int row = aElm ->getRowNum();
        CCLOG("col:%d row:%d",col,row);
    }
}

This does not compile right, and also I need to make new T object each time I call this function. What is the right way for this?

Upvotes: 0

Views: 81

Answers (1)

Ben Jackson
Ben Jackson

Reputation: 93700

Of course I don't know what your CCArray is but I can modify your function:

template<class T>
void UT::printArray(CCArray* arr)
{
    CCObject *aIt = NULL;  
    CCARRAY_FOREACH(arr,aIt )
    {
        T *aElm = static_cast<T*>(aIt );
        int col = aElm ->getColNum(); 
        int row = aElm ->getRowNum();
        CCLOG("col:%d row:%d",col,row);
    }
}

I've removed your second T type argument. You'd invoke this as printArray<myType>(arr) explicitly rather than having T inferred from your (unused) argument.

As someone said in a comment your best solution would be to read about iterators and make your CCArray return a proper begin() and end() and then you could use many standard algorithms (e.g. sort) against your container.

Upvotes: 2

Related Questions