指向模板函数的指针

Pointer to template function

本文关键字:指针 函数      更新时间:2023-10-16

我需要将函数作为参数传递,但它应该是模板函数。例如。

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

我需要使用这个函数作为方法的参数。

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);
}
};

这样做可能吗?

要明确的是,语言中没有所谓的指向模板函数的指针。存在指向从函数模板实例化的函数的指针。

我想这就是你想要的:

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

下面是一个简单的程序及其输出。

#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.
}

输出

20