How to define a template function so it automatically deduces parameter type

Started by
4 comments, last by alvaro 11 years, 6 months ago
Hi there,

I do have a bitses matrix class defined as follows:

template <class INT_TYPE,class CONTAINER_INT=uINT,
INT_TYPE ContainerSize=sizeof(CONTAINER_INT)*8,
class DATA_CONTAINER=BitsetDataContainer<INT_TYPE,CONTAINER_INT,ContainerSize> >
class BitsetMatrix
{
///code
};


And I have a function:

template <class INT_TYPE>
INT_TYPE Sum(const BitsetMatrix<INT_TYPE> &M)
{
INT_TYPE Rt;
if (!M.IsEmpty())
{
//count sum using another function
}
return Rt;
}


How to define this function that it deduces INT_TYPE argument automatically? In VC++ it works fine, in GCC I need to write:

BitsetMatrix<int> BM;
Sum<int>(BM);


How to define function Sum to avoid <int> in its call.

Regards
Advertisement
I only have a passing understanding of templates in C++, but the way I would do it is by making Sum be a template of the matrix type, and the matrix can provide a typedef to access the underlying INT_TYPE.
Quick code, I'm not sure if it's compilable or work, don't have time to test for now.

[source]template <class INT_TYPE,class CONTAINER_INT=uINT,
INT_TYPE ContainerSize=sizeof(CONTAINER_INT)*8,
class DATA_CONTAINER=BitsetDataContainer<INT_TYPE,CONTAINER_INT,ContainerSize> >
class BitsetMatrix
{
public:
typedef INT_TYPE IntType;
///code
};


template <class T>
typename T::IntType Sum(const T &M)
{
typename T::IntType Rt;
if (!M.IsEmpty())
{
//count sum using another function
}
return Rt;
}

[/source]

https://www.kbasm.com -- My personal website

https://github.com/wqking/eventpp  eventpp -- C++ library for event dispatcher and callback list

https://github.com/cpgf/cpgf  cpgf library -- free C++ open source library for reflection, serialization, script binding, callbacks, and meta data for OpenGL Box2D, SFML and Irrlicht.

@wqking: that looks promising :]
Oh, after reading alvaro's reply again, I just found his opinion is exactly same as my code.

https://www.kbasm.com -- My personal website

https://github.com/wqking/eventpp  eventpp -- C++ library for event dispatcher and callback list

https://github.com/cpgf/cpgf  cpgf library -- free C++ open source library for reflection, serialization, script binding, callbacks, and meta data for OpenGL Box2D, SFML and Irrlicht.


Oh, after reading alvaro's reply again, I just found his opinion is exactly same as my code.


Of course! I just thought you were implementing my suggestion. :)

This topic is closed to new replies.

Advertisement