指向模板函数的指针
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
我需要将我的函数作为参数传递,但它应该是模板函数。例如。
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