我想做这样的事情:
我希望用户提供一个返回类型和一个参数(总是只有一个),然后我希望用户能够提供与该条件匹配的函数的指针。我将使用它来创建一个定时事件。
这里的问题是通常使用模板时,您必须提供T并创建一个新的类实例,但是在这种情况下,我需要使用它作为运行时。例如:

TimeEvent *explode  = new TimeEvent(int (the return type),data (the argument), explodeFunc (the function pointer);

然后将创建并设置函数指针。然后,调用者只需执行explode.call()即可对其进行调用。
我怎样才能实现这样的目标?

谢谢

最佳答案

好吧boost.function + boost.bind可以用于此目的:

int explodeFunc( std::string const & someString ) {
     std::cout << someString << " exploded" << std::endl;
     return 1;
}

然后...
boost::function< int() > timeEvent = boost::bind(explodeFunc, "The world");
int retVal = timeEvent();

但我不确定这是否是您要寻找的

这里是一个没有提升的简单版本:
#include <iostream>
#include <string>

template< typename R >
struct TimeEvent {
    virtual ~TimeEvent(){}
    virtual R call() = 0;
};

template< typename R, typename ParamType >
struct TimeEventT : TimeEvent<R> {
    typedef R (*callback_type)( ParamType const & );
    typedef ParamType param_type;
    TimeEventT( param_type const & param, callback_type cb )
        : TimeEvent<R>()
        , callback_( cb )
        , param_( param )
    {}

    R call() {
        return callback_( param_ );
    }

protected:
    callback_type callback_;
    param_type param_;
};

template< typename R, typename ParamType, typename ParamValueT >
TimeEvent<R> * create_time_event(
    R (*cb)(ParamType const &),
    ParamValueT const & param
) {
    return new TimeEventT<R, ParamType>( param, cb );
}

int explodeFunc( std::string const & param ) {
    std::cout << param << " exploded" << std::endl;
    return 1;
}

std::string explodeFuncString( std::string const & param ) {
    return param + " really exploded this time";
}

int main(){
    std::string param = "The world";
    TimeEvent<int> * timeEvent1 = create_time_event( explodeFunc, param );
    if( timeEvent1 ) {
        timeEvent1->call();
        delete timeEvent1;
    }
    TimeEvent<std::string> * timeEvent2 = create_time_event( explodeFuncString, param );
    if( timeEvent2 ) {
        std::cout << timeEvent2->call() << std::endl;
        delete timeEvent2;
    }
    return 0;
}

希望您能想到,并使其适合您的需求。

高温超导

编辑:更新了模板化的返回类型。
*使create_time_event更加用户友好

关于c++ - 模板化函数指针?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3928835/

10-11 23:12
查看更多