使用函数指针调用函数模板
Call a function template using a function pointer
我需要使用一个函数模板,该模板通过一个函数指针在头文件中可用,该指针可用作结构体成员。
例如:文件:mytemplate.h
template<typename T> const bool GT(const T& pa_roIN1, const T& pa_roIN2)
{
bool temp = false;
if(pa_roIN1 > pa_roIN2){
temp = true;
}
return temp;
}
template<typename T> const bool EQ(const T& pa_roIN1, const T& pa_roIN2)
{
bool temp = false;
if(pa_roIN1 == pa_roIN2){
temp = true;
}
return temp;
}
template<typename T> const bool GE(const T& pa_roIN1, const T& pa_roIN2)
{
bool temp = false;
if(pa_roIN1 >= pa_roIN2){
temp = true;
}
return temp;
}
文件:mystruct.h:
struct mystruct {
std::string funcName;
bool (*funcPtr)(int,int);
};
typedef std::map<int, mystruct> mystructList;
文件:mycpp.cpp:
#include "mytemplate.h"
#include "mystruct.h"
mystruct MyGreaterStruct[3] = {
{"GREATER_THAN", >},
{ "EQUAL", &EQ},
{ "GREATER_N_EQUAL", &GE}
};
mystructList MyList;
int main(void)
{
int size = sizeof(MyGreaterStruct)/sizeof(mystruct);
for(int i = 0; i < size; i++) {
MyList.insert(std::pair<int, mystruct>(i,MyGreaterStruct[i])); }
for(mystructList::iterator iter = MyList.begin(); iter != MyList.end(); iter++) {
printf("nResult of func : %s for values 100,50 : %d",iter->second.funcName.c_Str(),iter->second->funcPtr(100,50));
}
}
我不确定这是正确的做法。但是没有结果打印到控制台上。
编译代码时得到的错误告诉您哪里出错了:
mycpp.cpp:8:1: error: no matches converting function ‘GT’ to type ‘bool (*)(int, int)’
};
^
mytemplate.h:1:33: note: candidate is: template<class T> const bool GT(const T&, const T&)
template<typename T> const bool GT(const T& pa_roIN1, const T& pa_roIN2)
^
无法实例化该模板以匹配函数指针的签名,因为模板接受两个引用作为实参,而指针接受两个int型实参。如果你不能改变结构或模板,并且你正在使用c++ 11,你可以尝试使用lambdas来代替:
mystruct MyGreaterStruct[3] = {
{"GREATER_THAN", [](int a, int b)->bool { return GT(a, b); } },
{ "EQUAL", [](int a, int b)->bool { return EQ(a, b); } },
{ "GREATER_N_EQUAL", [](int a, int b)->bool { return GE(a, b); } }
};
,但无论如何分割,都需要更改参数或使用一个小函数将参数从一种形式转换为另一种形式
相关文章:
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- C++如果两个模板函数都与参数列表匹配,将调用哪个模板
- 如何在类模板的成员函数中正确调用函数对象?正在生成 Visual Studio 编译器错误 C2440
- 为什么没有调用此模板类的复制构造函数?
- 调用类模板中隐式删除的复制构造函数
- 从模板化函数调用非模板化函数
- 从类似构造函数的调用返回模板化智能指针
- 从模板化类虚拟函数中调用的模板函数不正确
- 需要"模板<>"语法 --> 通过函数调用类模板
- 模板 使用数据数组调用函数时扩展参数包
- C++,当函子不是一个选项时,我如何编写带有自定义函数调用的模板化 RAII 包装器?
- 调用类模板的成员函数模板
- 如何从前面定义的另一个函数调用函数模板
- 未为派生类型调用函数模板专用化
- Lambda函数无法调用函数模板参数的静态函数
- 不能用函数参数调用函数模板
- 使用函数指针调用函数模板
- 调用函数模板时出错"No matching function"
- 为派生的可变参数类模板调用函数模板重载
- 使用C调用约定调用函数模板专门化