【问题标题】:Pointer to template function指向模板函数的指针
【发布时间】:2015-04-26 16:21:13
【问题描述】:

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

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

这样可以吗?

【问题讨论】:

  • 您建议从哪里获取argtype 类型的数据?

标签: c++ function class templates


【解决方案1】:

只是为了清楚地说明语言——没有什么叫做指向模板函数的指针。有指向从函数模板实例化的函数的指针。

我想这就是你要找的:

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

【讨论】:

  • 有什么理由不使用std::function,这可能会使其更具可读性。还是仅仅因为 OP 要求提供纯函数指针?
猜你喜欢
  • 1970-01-01
  • 2013-02-19
  • 1970-01-01
  • 2016-10-18
  • 2010-09-13
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多