Tuesday, 10 March 2015

Find the address of a function template

Find the address of a function template:

If we want to find the address of the function at any situation, there are number of ways available in C++.

For example, you may have a function that takes an argument of a pointer to another function. Of
course it’s possible that this other function might be generated from a template function.
See the below example to find the address of the function template.

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
template <typename T> void Fun(T*)
void MyFunc (void (*voidPtr)(int*))
template <class T>
void Fun2 (void (*voidPtr)(T*))
int main()
  MyFunc (&Fun<int>);
  MyFunc (&Fun);
  Fun2<int> (&Fun<int>);
  Fun2 (&Fun<int>);
  Fun2<int> (&Fun);
  getchar ();
  return 0;

This example demonstrates a number of different issues. First, even though you’re using
templates, the signatures must match – the function MyFunc ( ) takes a pointer to a function that takes
an int* and returns void, and that’s what the template f produces. Second, the function that
wants the function pointer as an argument can itself be a template, as in the case of the
template Fun2.

In main( ) you can see that type induction works here, too. The first call to MyFunc ( ) explicitly
gives the template argument for Fun, but since MyFunc ( ) says that it will only take the address of a
function that takes an int*, that part can be induced by the compiler.

With Fun2 ( ) the situation is even more interesting because there are two templates involved. The compiler cannot induce the type with nothing to go on, but if either Fun or Fun2 is given int, then the rest can be induced.

No comments: