任意类的const和非const成员函数的模板包装器 [英] Template wrapper for const and non const member functions of arbitrary classes

查看:84
本文介绍了任意类的const和非const成员函数的模板包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个模板化的类(包装器),该类可以包含所有可能的类(T)并使用这些类的成员函数(函数)做事(在这里评估)。

I want to have a templated class (wrapper), which can take all possible classes (T) and do stuff (here evaluate) with the member functions of these classes (function).

我发现了类似的请求,您可以看到此处此处,但都不能满足两个条件

I found similar requests, which you can see here and here, but neither could satisfy the two conditions below.

条件:


  1. 两者都是指向包装类中必须可以访问该类的实例(T * ptr)和一个指向成员函数(函数)的指针。

  1. Both, a pointer to the instance of the class ( T * ptr) and a pointer to the member function (function) must be accessible within the wrapper class.

包装类应起作用

以下代码仅适用于非const:

Here a code that works only for non-const:

#include <iostream>
#include <math.h>

template< class T, double (T::*fck) (double) >
struct Wrapper
{
  Wrapper( T * ptrT);

  double evaluate( double );

protected:

  T * myPtrT;
};


template< class T, double (T::*fck) (double) >
Wrapper<T, fck>::Wrapper( T * ptrT) : myPtrT(ptrT) {}


template< class T, double (T::*fck) (double) >
double Wrapper<T, fck>::evaluate( double s )
{ return (myPtrT->*fck)(s); }


struct kernel
{
  double gauss( double s )
  {
    return exp(-0.5*s*s);
  }
};

int main()
{
  kernel G;

  Wrapper<kernel, &kernel::gauss> myKernel ( &G );

  std::cout<< myKernel.evaluate(0.0) <<std::endl;
  std::cout<< myKernel.evaluate(0.3) <<std::endl;

  return 0;
}


推荐答案

包装器类是绝对必要的吗?您似乎正在尝试为提供具有标准签名的函数的类创建通用评估机制: double f(double)。使用 std :: function (C ++ 11)或 boost :: function (C ++)即可轻松解决03)。

Is the Wrapper class strictly necessary? It looks like you're trying to create a generic evaluation mechanism for classes that provide functions with a standard signature: double f(double). This is easily solved using std::function (C++11) or boost::function (C++03).

使用 boost :: function boost :: bind

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <math.h>

struct kernel
{
  double gauss( double s )
  {
    return exp(-0.5*s*s);
  }
};

int main()
{
    kernel G;

    typedef boost::function<double (double)> MyWrapper;

    MyWrapper w( boost::bind(&kernel::gauss, G, _1) );
    std::cout << w(0.0) << std::endl;
    std::cout << w(0.3) << std::endl;

    return 0;
}

这篇关于任意类的const和非const成员函数的模板包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆