使用函数指针调用函数模板

Call a function template using a function pointer

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

我需要使用一个函数模板,该模板通过一个函数指针在头文件中可用,该指针可用作结构体成员。

例如:

文件: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", &GT},
  { "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); } }
};

,但无论如何分割,都需要更改参数或使用一个小函数将参数从一种形式转换为另一种形式