Template function passes incorrect type
I have two classes that wrap an int and BOOLclass CMyInt: public CObject
{
int m_Value;
};
class CMyBool:public CObject
{
BOOL m_Value;
};and a template Test function that instantiates an object of any type ...template<class T> void Test()
{
T dummy;
};Now, depending of the order of Test function calls, the dummy gets instantiated as the type passed in the last function call.
So if in my application I (only) have this sequence of Test function calls ...Test<CMyBool>(); //dummy will be instantiated as CMyInt
Test<CMyInt>(); //dummy will be instantiated as CMyIntand when ...
Test<CMyInt>(); //dummy will be instantiated as CMyBool
Test<CMyBool>(); //dummy will be instantiated as CMyBoolAnyone ?
[802 byte] By [
zvenny] at [2007-11-20 11:00:31]

# 1 Re: Template function passes incorrect type
It has to be a compiler bug, since if you do it like this, it works
template<class T> void Test(T *i)
{
T dummy;
};
Test<CMyBool>(NULL); //dummy will be instantiated as CMyBool
Test<CMyInt>(NULL); //dummy will be instantiated as CMyInt
zerver at 2007-11-10 22:27:31 >

# 2 Re: Template function passes incorrect type
It's a bug:
Explicitly Specified Template Functions Not Overloaded Correctly ( http://support.microsoft.com/kb/240871/)
The fix:
template<class T> void Test(T *pt=0)
{
T dummy;
};
# 5 Re: Template function passes incorrect type
zerver: It looks like we posted at exactly the same time. Note optional parameter specification "=0" as suggested by MSDN.
Yeah, I made this conclusion based on testing. Had no idea it was listed at MSDN :wave:
zerver at 2007-11-10 22:31:43 >

# 6 Re: Template function passes incorrect type
Following the KB article explanation, I'd expect the bug to occur each time a templated function doesn't use ALL template parameters as either a return type or function argument. With this knowledge I've tested 2 of my apps in which I use similar template functions ...//app 1
template<class T,class V> BOOL App1Func(CAClass* pAObject,CString strName,V** ppValue)
{
...
}
//app 2
template<class T,class V> BOOL App2Func(CAnotherClass* pAnotherObject,CString strName,V** ppValue)
{
...
}Somehow for 1 of the apps, type T is always passed correctly although not used as return type or function argument type!?!?
Guess there's more to investigate than mentioned in the KB article SYMPTOMS section :confused:
Anyway, dummy arguments indeed solve it, so from now on I'll use that as a template function guideline :cool:
If anyone has more info to share about this subject, I'd be very happy to hear/read it !
zvenny at 2007-11-10 22:32:42 >
