如何在类/函数模板中传递void参数

Gri*_*fin 3 c++ membership templates class void

嘿,我正在尝试制作一个Button模板类,它是用 按下按钮(例如鼠标位置),以及指向应该调用的函数的指针.

然而按钮经常返回void并且不带参数(你按下按钮并且发生了一些事情:它们不接受任何参数,它们被按下然后只是做一些事情.)所以如何生成类成员函数,因为显然我可以"T具有空隙作为参数类型?

如果它有用,这是源代码:

    template<typename Return = void, typename Arg1 = void, typename Arg2 = void> 
class Button 
{
private:
    boost::function<Return (Arg1, Arg2)> Function;
    //Return (*Function)(Arg1, Arg2);              // this didn't work so i tried boost::function

public:
    void Activate(Arg1, Arg2){ Function(Arg1, Arg2) ;};

    void SetFunction(Return (*Function)(Arg1, Arg2)){
        this->Function= Function;};

    //constructors
    Button(){ Function= 0;};

    Button( Return (*Function)(Arg1, Arg2)){  
        this->Function = &Function; };
};
Run Code Online (Sandbox Code Playgroud)

Tho*_*ell 5

您可以指定void类型的模板规范,例如,您可以使用模板化类的以下变体button:

template <typename rtnVal, typename Val1, typename Val2>
class Button {
private:
    rtnVal(*Function)( Val1 val1, Val2 val2 );

public:
    Button() : Function( nullptr ) {}

    void SetFunction( rtnVal(*func)(Val1, Val2) ) {
        Function = func;
    }

    rtnVal RunFunction( Val1 val1, Val2 val2 ) { return Function( val1, val2 ); }
};

// Special void type, accepting arguments overload:
template < typename Val1, typename Val2 >
class Button< void, Val1, Val2 > {
private:
    void(*Function)(Val1 val1, Val2 val2);

public:
    Button() : Function( nullptr ) {}

    void SetFunction( void(*func)(Val1, Val2) ) {
        Function = func;
    }

    void RunFunction( Val1 val1, Val2 val2 ) { return Function( val1, val2 ); }

};

// Pure void type:
template<>
class Button<void, void, void> {
private:
    void(*Function)( void );

public:
    Button() : Function( nullptr ) {}

    void SetFunction( void(*func)() ) {
        Function = func;
    }

    void RunFunction() { 
        return Function();
    }
};
Run Code Online (Sandbox Code Playgroud)

然后,这允许您初始化并使用void作为参数,例如,给定void函数Print(),以下现在将是有效的:

void Print()
{
    std::cout << "Function has been called" << std::endl;
}

int main()
{
    Button< void, void, void > btn;

    btn.SetFunction( Print );

    btn.RunFunction();

    std::cout << "Finished";
}
Run Code Online (Sandbox Code Playgroud)

我希望这有助于清理事情!:)

注意:nullptr是一个C++ 0x关键字,如果您的编译器没有实现它使用#define nullptr 0