c++ - 函数作为模板参数

标签 c++ c++11 templates dry

我试图通过编写模板函数来避免这种重复代码。

#include <algorithm>
class X {

public:
void get_amin(double *a){}
void set_amin(double a){}

void get_bmin(double *b){}
void set_bmin(double b){}

//...many pairs like above

};
int main(){
      X *x1 = new X;
      X *x2 = new X;

      //code that will be repeated
      {
          double x1_amin;
          x1->get_amin(&x1_amin);
          double x2_amin;
          x2->get_amin(&x2_amin);          
          x1->set_amin(std::min(x1_amin, x2_amin));
      }
      //repeatation
      {          
          double x1_bmin;
          x1->get_bmin(&x1_bmin);
          double x2_bmin;
          x2->get_bmin(&x2_bmin);          
          x1->set_bmin(std::min(x1_bmin, x2_bmin));
      }
      //
      delete x1;
      delete x2;
}

现在我的尝试如下。看来我能够编写模板但不能使用它。 stack overflow 上的其他帖子主要关注如何编写模板。我也找不到使用类成员函数的示例。

#include <algorithm>
#include <functional>
class X {

public:
void get_amin(double *a){}
void set_amin(double a){}

void get_bmin(double *b){}
void set_bmin(double b){}

//...many pairs like above

};

template <typename F11,typename F12, typename F2>
void templatisedFunction(F12 f11,F12 f12,F2 f2)
{
    double x1_amin;
    f11(&x1_amin);

    double x2_amin;
    f12(&x2_amin);       

    f2(std::min(x1_amin, x2_amin));
}

int main(){

    X *x1 = new X;
    X *x2 = new X;

    //templatisedFunction(x1->get_amin,x2->get_amin,x1->set_amin);
    //templatisedFunction(x1->get_amin(double*),x2->get_amin(double*),x1->set_amin(double));


    //templatisedFunction<x1->get_amin(double*),x2->get_amin(double*),x1->set_amin(double)>();
    //templatisedFunction<x1->get_amin,x2->get_amin,x1->set_amin>();

    std::function<void(X*)> memfun(&X::get_amin);//not sure here
    //templatisedFunction<x1->get_amin,x2->get_amin,x1->set_amin>();

    //
    delete x1;
    delete x2; 
}

最佳答案

void (X::*getf)(double *)void (X::*setf)(double) 是指向两个指针的函数签名您需要的成员函数。

使用 C++11:

int main()
{
    X x1;
    X x2;

    auto lamb = [&](void (X::*getf)(double *), void (X::*setf)(double))
    {
        double x1_amin;
        (x1.*getf)(&x1_amin);
        double x2_amin;
        (x2.*getf)(&x2_amin);          
        (x1.*setf)(std::min(x1_amin, x2_amin));
    };

    lamb(&X::get_amin, &X::set_amin);
    lamb(&X::get_bmin, &X::set_bmin);
    return 0;
}

关于c++ - 函数作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42866767/

相关文章:

c++ - 一台服务器多客户端 C/C++

c++ - 源代码中的注释

c++ - 如何禁止赋值

C++ 移动类,里面有线程

html - 仅使用纯 html 和 css 在多个列上添加 html 内容?

c++ - 模板代码中的类型不完整

c++ - 在 MFC Direct3D 应用程序中使用 DXUTSetWindow

c++ - Qt Creator编译错误 "::swprintf and::vswprintf has not been declared"

c++ - 如何使用模板函数设置不同类型的值?

c++ - 如何让 std::thread 停止?