This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: template function explicit instantiation


Gokhan Kisacikoglu <kisa@centropolisfx.com> writes:

> I am trying to instantiate a template function explicitly to pass as an
> argument to another function, here's an example:
> 
> #include <iostream>
> using namespace std;
> 
> typedef void * (_KMP_FN_)(void *);
> 
> template <class T>
> void doIt( T *_t )
> {
>     cerr << (*_t) << endl;
> }
> 
> void doFn( _KMP_FN_ _fn )
> {
>     int i = 5;
>     _fn(&i);
> }
> 
> int main(void)
> {
>     int i = 10;
>     
>     doIt(&i);
>     doFn( (_KMP_FN_ *) doIt <int> );
>     
>     return 0;
> }
> 
> I tried instantiating doIt(int *) just to make sure that an instance of
> the function can be found, though I expect the compiler to instantiate
> the function automatically. Anyway, if anyone can figure out the syntax,
> please let me know...
> 
> I am using gcc 3.2, This is the error:
> 
> t.cpp: In function `int main()':
> t.cpp:29: no matches converting function `doIt' to type
> `void*(*)(void*)'
> t.cpp:8: candidates are: template<class T> void doIt(T*)

Either

int main(void)
{
    doFn( (_KMP_FN_*)static_cast<void (*)(int*)>(doIt<int>) );
    return 0;
}


or


int main(void)
{
   int i = 10;
  
   doIt(&i);
   void (*foo)(int*) = doIt<int>;
    
   doFn( (_KMP_FN_*)(foo) );
   return 0;
}


Now, a few quick observations:

1. Names starting with an underscore are reserved for the language
   implementation (compiler and library).

2. It's a good practice to use C++-style typecasts rather than C-style
   ones. The C++ typecasts are safer you can spot them quickly. On
   your case, use reinterpret_cast<_KMP_FN*>(bla). This one is not
   safer (actually, reinterpret_cast is the C++ word for unsafe
   typecasts) but it's easier to spot.

3. The 'return 0' at the end of the program is unnecessary. The
   compiler does it for you.

-- 
Oscar



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]