任意类的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.
条件:
-
两者都是指向包装类中必须可以访问该类的实例(T * ptr)和一个指向成员函数(函数)的指针。
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 $ C ++ 03中的c $ c>:
#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;
}