0

我想在 muParser Link中定义一个新函数。-ClassFunctionWrapper应该被注册。

class FunctionWrapper
{
public:
virtual double Evaluate(const double*, int) = 0;
};

-MethodDefineFun需要一个字符串和一个函数指针。我怎样才能使这个指针指向函数Evaluate

我想打电话给DefineFun另一个班级......像这样:

bool OtherClass::RegisterFunction(std::string name, FunctionWrapper *wrapper)
{
   fParser.DefineFun(name, wrapper->????);
}

谢谢

4

2 回答 2

0

您是否考虑过 std::function 作为您的包装器?与 std::bind 或 lambdas 结合使用,它可能可以完成您需要的一切。例如,

#include <unordered_map>
#include <functional>
#include <exception>
#include <memory>
#include <string>
#include <iostream>

class Evaluator
{
public:
    virtual ~Evaluator() {}
    virtual double Evaluate( const double*, int ) = 0;
    // ...
};

class Registry
{
public:
    typedef std::function<double(const double*, int)> Fn; // For easier reading

    class NameNotFoundException : public std::exception {};

    void Register( const std::string& name, const Fn& fn )
    {
        _regMap[ name ] = fn;
    }

    void Call( const std::string& name, const double* const data, const int size )
    {
        auto it = _regMap.find( name );
        if( it == _regMap.end() )
        {
            throw NameNotFoundException();
        }

        it->second( data, size ); // Call fn
    }

private:
    std::unordered_map<std::string, Fn> _regMap;
};

class EvaluatorImpl : public Evaluator
{
public:
    double Evaluate( const double* const data, const int size ) 
    { /*...*/
        for( int n=0; n < size; ++n )
            std::cout << data[n] << '\n';
        return 0;     
    }
    // ...
};

int main()
{
    std::shared_ptr<Evaluator> eval( new EvaluatorImpl() );

    Registry reg;

    // Could use a lambda here instead of std::bind
    reg.Register( "Bob", 
        std::bind( &Evaluator::Evaluate, eval, std::placeholders::_1, std::placeholders::_2 ) );

    const double data[] = { 1, 2, 3 };
    int size = 3;

    reg.Call( "Bob", data, size );
}
于 2013-05-17T17:48:47.390 回答
0
于 2013-05-17T22:56:15.833 回答