T
Tim Frink
Hi,
I want to use a callback function together with
templates. Let's say I've this code:
File a.h:
class A
{
private:
template< typename T >
void func( bool( T::*f)(void) );
};
-----------------
File a.cc:
template< typename T >
void A::func( bool( T::*f)(void) )
{
f();
}
------------------
and another class B that uses "func":
File b.cc:
#include "a.h"
bool B::func2(void)
{
return true;
}
void B::func3()
{
A a;
a->func( &B::func2 );
}
During compilation I get the error
undefined reference to `void A::func<B>(bool (B::*)())'.
The problems seem to be that during compilation of class B, the
template function A::func is not completely known (just the
function declaration of the header file, but not the function
definition). I assume that one solution is to move the function
body of A::func into the header file a.h to make it visible during
compilation of class B.
However, this seems not to be the best solution because I must
reveal the implementation of A::func to anyone who wants to use
it. Without templates, I could compile class A into a library
and just provide the header file a.h together with the library.
So, the users would not see the implementation of class A.
However, when I move code from the source file into the header
file, I show my implementation which I would like to avoid.
Are there any solutions for that? Or are templates in general
crucial when source code must be kept closed?
Best regards,
Tim
I want to use a callback function together with
templates. Let's say I've this code:
File a.h:
class A
{
private:
template< typename T >
void func( bool( T::*f)(void) );
};
-----------------
File a.cc:
template< typename T >
void A::func( bool( T::*f)(void) )
{
f();
}
------------------
and another class B that uses "func":
File b.cc:
#include "a.h"
bool B::func2(void)
{
return true;
}
void B::func3()
{
A a;
a->func( &B::func2 );
}
During compilation I get the error
undefined reference to `void A::func<B>(bool (B::*)())'.
The problems seem to be that during compilation of class B, the
template function A::func is not completely known (just the
function declaration of the header file, but not the function
definition). I assume that one solution is to move the function
body of A::func into the header file a.h to make it visible during
compilation of class B.
However, this seems not to be the best solution because I must
reveal the implementation of A::func to anyone who wants to use
it. Without templates, I could compile class A into a library
and just provide the header file a.h together with the library.
So, the users would not see the implementation of class A.
However, when I move code from the source file into the header
file, I show my implementation which I would like to avoid.
Are there any solutions for that? Or are templates in general
crucial when source code must be kept closed?
Best regards,
Tim