user4602510
user4602510

Reputation:

Pointer to template function

I need to pass my function as a parameter, but it should be template function. For instance.

template <class rettype, class argtype> rettype test(argtype x)
{
    return (rettype)x;
}

I need to use this function as an argument for method.

template <class type,class value> class MyClass
{
    // constructors, etc

    template <class type,class value> void myFunc(<function should be here with parameters > ) {
     rettype result = function(argtype);
}
};

Is it possible to do this way ?

Upvotes: 0

Views: 150

Answers (1)

R Sahu
R Sahu

Reputation: 206567

Just to be clear on the language -- there is nothing called a pointer to a template function. There are pointers to functions that are instantiated from function templates.

I think this is what you are looking for:

template <class type, class value> struct MyClass
{
   template <class rettype, class argtype> 
   rettype myFunc( rettype (*function)(argtype), argtype v)
   {
      return function(v);
   }
};

Here's a simple program and its output.

#include <iostream>

template <class rettype, class argtype> rettype test(argtype x)
{
    return (rettype)x;
}

template <class type,class value> struct MyClass
{
   template <class rettype, class argtype> 
   rettype myFunc( rettype (*function)(argtype), argtype v)
   {
      return function(v);
   }
};


int main()
{
   MyClass<int, double> obj;
   std::cout << obj.myFunc(test<int, float>, 20.3f) << std::endl;
                           // ^^^ pointer to a function instantiated
                           // from the function template.
}

Output

20

Upvotes: 1

Related Questions