模板类构造函数,指向成员函数的指针作为参数

时间:2012-09-05 12:45:42

标签: c++ templates function-pointers

我有以下设置,这让我头疼,因为我没有看到问题:

ValidationModule module = ValidationModule(std::vector<FilterFlag>(0));
Settings validationSettings = Settings("Validation Settings");
validationSettings.registerFloat("test", module, &ValidationModule::setRatio, &ValidationModule::getRatio, 0.0f, 1.0f);

registerFloatValidationModule

的成员函数有两个指示

ValidationModule.h

// constructor
ValidationModule(const std::vector<FilterFlag>& filterFlags, float ratio = 0.7f);

// getter and setter, which are passed to Settings::registerFloat
inline void setRatio(float value) { _ratio = value; }
inline float getRatio() const { return _ratio; }

Settings.h

template<class TClass>
inline void Settings::registerFloat(const std::string& name, TClass owner, void (TClass::*setter)(float), float (TClass::*getter)() const, float minValue, float maxValue)
{
    CallBackToMemberSingleArg<float, TClass>* setterCallback = new CallBackToMemberSingleArg<float, TClass>(owner, setter);
    CallBackToMemberReturn<float, TClass>* getterCallback = new CallBackToMemberReturn<float, TClass>(owner, getter);
    // some unrelated processing
    [...]
}

编译器为CallBackToMemberSingleArgCallBackToMemberReturn的两个构造函数提供了以下错误

No matching constructor for initialization of 'CallBackToMemberSingleArg<float, ValidationModule>'
No matching constructor for initialization of 'CallBackToMemberReturn<float, ValidationModule>'

以下是构造函数声明

Callback.h

template <typename TParam>
class CallBackSingleArg
{
public:
    virtual ~CallBackSingleArg() { }
    virtual void call(const TParam& p) = 0;
};

template <typename TParam, typename TClass>
class CallBackToMemberSingleArg : public CallBackSingleArg<TParam>
{
    void (TClass::*function)(const TParam&);
    TClass* object;
public:
    CallBackToMemberSingleArg(TClass* object, void(TClass::*function)(const TParam&)) : object(object), function(function) { };
    void call(const TParam& p) {
        (*object.*function)(p);
    }
};

template <typename TParam>
class CallBackReturn
{
public:
    virtual ~CallBackReturn() { }
    virtual TParam call() = 0;
};

template <typename TParam, typename TClass>
class CallBackToMemberReturn : public CallBackReturn<TParam>
{
    TParam (TClass::*function)();
    TClass* object;
public:
    CallBackToMemberReturn(TClass* object, TParam(TClass::*function)()) : object(object), function(function) { };
    TParam call() {
        return (*object.*function)();
    }
};

我尝试将实际的setter更改为void setRatio(const float& value),因为CallBackToMemberSingleArg采用了const引用参数,但这没有帮助,并且对CallBackToMemberReturn的构造函数的调用也给出了以上错误,所以必须有其他东西,我无法看到。

1 个答案:

答案 0 :(得分:0)

您将TClass作为第一个参数传递给CallBackToMemberSingleArg构造函数,但预计会TClass*