Your source pointer type must depend on the target pointer type because the
pRetargetingFunction
depends on the target pointer type. An explicit cast is not useful for template pointers.
example:
#pragma once
#include <stdio.h>
#include <tchar.h>
template <typename T>
class Targeter
{
public:
static void RetargetFunction(T* p,const TCHAR* name)
{
_tprintf(__T("Targeter(%s)\r\n"),name);
}
};
template <typename T>
class ConstTargeter
{
public:
static void RetargetFunction(const T* p,const TCHAR* name)
{
_tprintf(__T("ConstTargeter(%s)\r\n"),name);
}
};
template <typename Source,typename T>
void Connect(Source* pSource, T* pTarget)
{
pSource->m_pTarget = pTarget;
pSource->pRetargetingFunction = &Targeter<T>::RetargetFunction;
return;
}
template <typename Source,typename T>
void Connect(Source* pSource,const T* pTarget)
{
pSource->m_pTarget = pTarget;
pSource->pRetargetingFunction = &ConstTargeter<T>::RetargetFunction;
return;
}
template <class T>
class tSourceA
{
typedef void (*RETARGET)(T*,const TCHAR*);
static void intern(T* p,const TCHAR* name)
{
_tprintf(__T("internA(%s)\r\n"),name);
}
public:
tSourceA(){ m_pTarget=0; pRetargetingFunction=&tSourceA::intern; }
~tSourceA(){ pRetargetingFunction(m_pTarget,__T("tSourceA")); }
T* m_pTarget;
RETARGET pRetargetingFunction;
};
template <class T>
class tSourceB
{
typedef void (*RETARGET)(T*,const TCHAR*);
static void intern(T* p,const TCHAR* name)
{
_tprintf(__T("internB(%s)\r\n"),name);
}
public:
tSourceB(){ m_pTarget=0; pRetargetingFunction=&tSourceB::intern; }
~tSourceB(){ pRetargetingFunction(m_pTarget,__T("tSourceB")); }
T* m_pTarget;
RETARGET pRetargetingFunction;
};
int _tmain(int argc, _TCHAR* argv[])
{
{ tSourceA<int> x;
int ai[]={1,2,3};
Connect(&x,ai);
}
{ tSourceA<const int> x;
const int ai[]={1,2,3};
Connect(&x,ai);
}
{ tSourceB<char> x;
char ai[]={'1','2','3'};
Connect(&x,ai);
}
{ tSourceB<const char> x;
const char ai[]={'1','2','3'};
Connect(&x,ai);
}
_gettch();
return 0;
}
result:
<br />
Targeter(tSourceA)<br />
ConstTargeter(tSourceA)<br />
Targeter(tSourceB)<br />
ConstTargeter(tSourceB)<br />
You cannot mix none const source classes with const target types and vice versa. Because the retargeting function depends on the target type.
i hope i could help.
regards.