指向模板函数的指针
Pointer to template function
我需要将函数作为参数传递,但它应该是模板函数。例如。
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
相关文章:
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址